python pandas - 修改索引日期

时间:2016-12-19 14:48:28

标签: python date pandas

我的pandas dataframe 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

1 个答案:

答案 0 :(得分:2)

您可以使用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'>