【问题标题】:python pandas - modifying index datespython pandas - 修改索引日期
【发布时间】:2016-12-19 14:48:27
【问题描述】:

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

【问题讨论】:

  • 您不能修改日期时间输出格式而不转换为无用的字符串,因为您不能像使用日期时间那样对字符串执行算术运算

标签: python date pandas


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2015-03-30
    • 2015-11-08
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多