gpt4 book ai didi

python - 未知的字符串格式,python 错误

转载 作者:行者123 更新时间:2023-11-30 22:35:24 24 4
gpt4 key购买 nike

我有如下索引:

Index(['2000-02-29 00:00:00_y', '2000-03-31 00:00:00_y',
'2000-04-30 00:00:00_y', '2000-05-31 00:00:00_y',
'2000-06-30 00:00:00_y', '2000-07-31 00:00:00_y',......

并且厌倦了通过以下方式更改为日期时间格式:

df.index.to_datetime())

现在我收到错误:

ValueError: Unknown string format

如何解决这个问题?

最佳答案

对 str 进行切片以删除无关的 '_y' 然后进行转换:

In[123]:
pd.to_datetime(index.str[:-2])

Out[123]:
DatetimeIndex(['2000-02-29', '2000-03-31', '2000-04-30', '2000-05-31',
'2000-06-30', '2000-07-31'],
dtype='datetime64[ns]', freq=None)

请注意pd.Index.to_datetime()引发 DeprecationWarning 因此您应该使用顶级 to_datetime相反。

请注意,默认情况下,时间部分不会显示,因为它等于'00:00:00',但它是完整的日期时间:

In[124]:
pd.to_datetime(index.str[:-2])[0]

Out[124]: Timestamp('2000-02-29 00:00:00')

关于python - 未知的字符串格式,python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44586920/

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