pandas :将YYYYQQ值的索引转换为日期时间对象 [英] Pandas: Converting index of YYYYQQ values to datetime object
本文介绍了 pandas :将YYYYQQ值的索引转换为日期时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下DataFrame:
I have the following DataFrame:
df = pd.DataFrame({'A':[1,2,3],'B':[4,3,2]},index = ['201701','201702','201703'])
其中字符串值的索引是日期,格式为YYYYQQ(季度数据).
where the index of string values are dates in the format YYYYQQ (quarterly data).
当我尝试将其转换为日期时间对象时,出现错误:
When I try to convert this into a datetime object, I got the error:
pd.to_datetime(df.index)
....
ValueError: month must be in 1...12
我认为这必须归因于to_datetime推断df.index的格式,但我找不到解决方法.有帮助吗?
I feel this has to be due to the format the to_datetime is inferring df.index is, but I can't find a work around. Any help?
更新:@Zero的答案也有效,但这也最终成为一种解决方案:
Update: @Zero's answer also works, but this ended up being a solution too:
pd.to_datetime([x[:-2] + str(int(x[-2:])*3) for x in df.index], format = '%Y%m')
推荐答案
使用
In [2325]: [pd.to_datetime(x[:4]) + pd.offsets.QuarterBegin(int(x[5:])) for x in df.index]
Out[2325]:
[Timestamp('2017-03-01 00:00:00'),
Timestamp('2017-06-01 00:00:00'),
Timestamp('2017-09-01 00:00:00')]
这篇关于 pandas :将YYYYQQ值的索引转换为日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文