python pandas - 修改索引日期

标签 python date pandas

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

相关文章:

sql-server - 将年日月转换为月日

java - 对链表方法内的日期进行排序

python - 在 Pandas 中迭代生成列名

python - 计算每天发生的观察次数

python - 添加到同一个字典的不同生成器返回相同的值

python - cherrypy SessionAuth 不起作用?

java - 如何在不使用异常的情况下检查日期是否符合特定的日期格式?

python - 翻转已排序数据框的排序顺序

python - Django - 某些 View 的用户权限?

python - 如何改进我的算法运行时间? cpoptimithe 不建议