Pandas:更改数据帧日期索引格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49168546/
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
Pandas: changing dataframe date index format
提问by Maxi
Would like to change the Date index of the dataframe from the default style into '%m/%d/%Y' format.
想将数据框的日期索引从默认样式更改为“%m/%d/%Y”格式。
In: df
Out:
Date Close
2006-01-24 48.812471
2006-01-25 47.448712
2006-01-26 53.341202
2006-01-27 58.728122
2006-01-30 59.481986
2006-01-31 55.691974
df.index
索引
Out:
DatetimeIndex(['2006-01-04', '2006-01-05', '2006-01-06', '2006-01-09',
'2006-01-10', '2006-01-11', '2006-01-12', '2006-01-13',
'2006-01-17', '2006-01-18',
...
'2018-02-21', '2018-02-22', '2018-02-23', '2018-02-26',
'2018-02-27', '2018-02-28', '2018-03-01', '2018-03-02',
'2018-03-05', '2018-03-06'],
dtype='datetime64[ns]', name=u'Date', length=3063, freq=None)
Into:
进入:
In: df1
Out:
Date Close
01/24/2006 48.812471
01/25/2006 47.448712
01/26/2006 53.341202
01/27/2006 58.728122
01/28/2006 59.481986
01/29/2006 55.691974
I tried this method before...
我之前试过这个方法...
df1.index = pd.to_datetime(df.index, format = '%m/%d/%Y')
df1.index = df.dt.strftime('%Y-%m-%d')
AttributeError: 'DataFrame' object has no attribute 'dt'
回答by jezrael
Use DatetimeIndex.strftime
- instead dt
need index
:
使用DatetimeIndex.strftime
- 而不是dt
需要index
:
df1.index = pd.to_datetime(df1.index, format = '%m/%d/%Y').strftime('%Y-%m-%d')
What is same:
什么是相同的:
df1.index = pd.to_datetime(df1.index, format = '%m/%d/%Y')
df1.index = df1.index.strftime('%Y-%m-%d')
EDIT if need convert DatetimeIndex
to another string format:
如果需要转换DatetimeIndex
为另一种字符串格式,请编辑:
print (df1.index)
DatetimeIndex(['2006-01-24', '2006-01-25', '2006-01-26', '2006-01-27',
'2006-01-30', '2006-01-31'],
dtype='datetime64[ns]', name='Date', freq=None)
df1.index = df1.index.strftime('%m/%d/%Y')
print (df1)
Close
01/24/2006 48.812471
01/25/2006 47.448712
01/26/2006 53.341202
01/27/2006 58.728122
01/30/2006 59.481986
01/31/2006 55.691974