我的 pandas 数据框 df 有一个索引和一个列“A”,其中
type(df.index)
给出
pandas.tseries.index.DatetimeIndex
如何切换日期中的数字,以便:
A
timestamp
2015-03-05 13:51:00 71.000000
2015-03-05 13:52:00 71.600000
2015-03-05 13:53:00 72.500000
2015-03-05 13:54:00 73.142857
2015-03-05 13:55:00 77.625000
变成这样:
A
timestamp
03-05-2015 13:51:00 71.000000
03-05-2015 13:52:00 71.600000
03-05-2015 13:53:00 72.500000
03-05-2015 13:54:00 73.142857
03-05-2015 13:55:00 77.625000
最佳答案
您可以使用DatetimeIndex.strftime
,但是索引类型是字符串,而不是日期时间:
#maybe is necessary swap %m with %d if first is day not month
df.index = df.index.strftime('%m-%d-%Y %H:%M:%S')
print (df)
A
03-05-2015 13:51:00 71.000000
03-05-2015 13:52:00 71.600000
03-05-2015 13:53:00 72.500000
03-05-2015 13:54:00 73.142857
03-05-2015 13:55:00 77.625000
print (df.index)
Index(['03-05-2015 13:51:00', '03-05-2015 13:52:00', '03-05-2015 13:53:00',
'03-05-2015 13:54:00', '03-05-2015 13:55:00'],
dtype='object')
print (type(df.index[0]))
<class 'str'>
关于python pandas - 修改索引日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41225153/