我有这样的索引
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')
并需要将其转换为datetime%H:%M:%S格式 我怎么能改变它?
答案 0 :(得分:1)
我认为你需要:
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)