Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

python - Parse_dates in Pandas

The following code can't parse my date column into dates from csv file.

data=pd.read_csv('c:/data.csv',parse_dates=True,keep_date_col = True) 

or

data=pd.read_csv('c:/data.csv',parse_dates=[0]) 

data is like following

date          value 
30MAR1990    140000 
30JUN1990    30000  
30SEP1990    120000  
30DEC1990    34555

What did I do wrong? Please help!

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a non-standard format, so not caught by the default parser, you can pass your own:

In [11]: import datetime as dt

In [12]: dt.datetime.strptime('30MAR1990', '%d%b%Y')
Out[12]: datetime.datetime(1990, 3, 30, 0, 0)

In [13]: parser = lambda date: pd.datetime.strptime(date, '%d%b%Y')

In [14]: pd.read_csv(StringIO(s), parse_dates=[0], date_parser=parser)
Out[14]:
        date  value
0 1990-03-30  140000
1 1990-06-30   30000
2 1990-09-30  120000
3 1990-12-30   34555

Another option is to use to_datetime after you've read in the strings:

df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...