Skip to main content
 首页 » 编程设计

python pandas之修改索引日期

2024年10月17日8artech

我的 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'>