gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:14:37 26 4
gpt4 key购买 nike

我有这样的索引

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com