Python Pandas 从日期创建日期时间索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42932632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:15:12  来源:igfitidea点击:

Python Pandas create Date Time index from date

pythondatepandasdatetime

提问by jeangelj

I have the following python pandas dataframe df:

我有以下 python Pandas数据帧 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

我收到以下错误:ValueError:组装映射需要至少指定[年,月,日]:[日,月,年]丢失

回答by philshem

You should explicitly define the format

您应该明确定义格式

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

and not let Pandas guess

不要让Pandas猜

to_datetime() documentation

to_datetime() 文档

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

0 2013-01-06