简体   繁体   中英

Python Pandas create Date Time index from date

I have the following python pandas dataframe df:

    DATES       Sales
0   1/6/2013    5676
1   1/8/2014    45746
2   1/10/2015   42658
3   1/14/2015   890790
4   1/16/2016   5764
5   1/20/2014   7898

I need to change DATES to a Date Time Index, so that i can resample it.

But when I do this

pd.to_datetime(df,infer_datetime_format=True)

I get the following error: ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

You should explicitly define the format

pd.to_datetime(df['DATES'],format='%m/%d/%Y')

and not let Pandas guess

to_datetime() documentation

To set a datetime as an index

df = df.set_index(pd.DatetimeIndex(df['DATES']))

Works for non-padded month and day:

import pandas as pd
d = {'1/6/2013' : 5676}
df = pd.DataFrame(d.items(), columns=['DATES', 'Sales'])
df['DATES'] = pd.to_datetime(df['DATES'],format='%m/%d/%Y')

0 2013-01-06

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM