pandas - 如何在 Pandas 中将索引转换为日期时间?

标签 pandas indexing time-series

我有这样的索引

Index(['00:00:00', '00:15:00', '00:30:00', '00:45:00', '01:00:00', '01:15:00',
       '01:30:00', '01:45:00', '02:00:00', '02:15:00', '02:30:00', '02:45:00'],
      dtype='object', name='time') 

并需要将其转换为日期时间 %H:%M:%S 格式
我怎样才能改变它?

最佳答案

我认为你需要:

idx = pd.Index(['00:00:00', '00:15:00', '00:30:00', '00:45:00', '01:00:00', '01:15:00',
       '01:30:00', '01:45:00', '02:00:00', '02:15:00', '02:30:00', '02:45:00'],
      dtype='object', name='time') 

对于 DatetimeIndex需要一些日期,默认添加今天:
print (pd.to_datetime(idx))
DatetimeIndex(['2018-01-25 00:00:00', '2018-01-25 00:15:00',
               '2018-01-25 00:30:00', '2018-01-25 00:45:00',
               '2018-01-25 01:00:00', '2018-01-25 01:15:00',
               '2018-01-25 01:30:00', '2018-01-25 01:45:00',
               '2018-01-25 02:00:00', '2018-01-25 02:15:00',
               '2018-01-25 02:30:00', '2018-01-25 02:45:00'],
              dtype='datetime64[ns]', name='time', freq=None)

或者可以添加自定义日期:
print (pd.to_datetime('2015-01-01 ' + idx))
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 00:15:00',
               '2015-01-01 00:30:00', '2015-01-01 00:45:00',
               '2015-01-01 01:00:00', '2015-01-01 01:15:00',
               '2015-01-01 01:30:00', '2015-01-01 01:45:00',
               '2015-01-01 02:00:00', '2015-01-01 02:15:00',
               '2015-01-01 02:30:00', '2015-01-01 02:45:00'],
              dtype='datetime64[ns]', freq=None)

另一种解决方案是创建 TimedeltaIndex :
print (pd.to_timedelta(idx))

TimedeltaIndex(['00:00:00', '00:15:00', '00:30:00', '00:45:00', '01:00:00',
                '01:15:00', '01:30:00', '01:45:00', '02:00:00', '02:15:00',
                '02:30:00', '02:45:00'],
               dtype='timedelta64[ns]', name='time', freq=None)

关于pandas - 如何在 Pandas 中将索引转换为日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48438456/

相关文章:

datetime - 如何根据索引列执行pandas drop_duplicates

R 使用 data.table 中的条件查找波高于给定值的频率和持续时间

mysql - 列中间隔 5 分钟的平均行数

python - 用于单词对共现计数的高效 Python?

python - 更改数据框索引值,同时保持其他列数据相同

java - @CompoundIndex 在 Spring Data MongoDB 中不起作用

python - bool 索引与 np.where

python - 无法在 Python 中使用 XlsxWriter 定义输出文件

python - 我怎样才能在子集上进行计算, Pandas 的方式,而不循环

mysql - 索引如何让速度快?