+-

我有一个Pandas DataFrame,它的列(标题)需要解析为datetime对象,以便可以将其转换为时间序列.
Title Gross Domestic Product: Quarter on Quarter growth: CVM SA %
224 2009 Q3 0.1
225 2009 Q4 0.4
226 2010 Q1 0.5
谁能指出最好的方法是什么?
我想要的输出是
Title Gross Domestic Product: Quarter on Quarter growth: CVM SA %
224 2009-09 0.1
225 2009-12 0.4
226 2010-03 0.5
最佳答案
如果“年”和“四分之一”之间没有空格,则大熊猫可以对其进行解析,因此您需要替换空格字符:
pd.to_datetime(df['Title'].str.replace(' ', '')) + pd.offsets.QuarterEnd(0)
Out:
0 2009-09-30
1 2009-12-31
2 2010-03-31
Name: Title, dtype: datetime64[ns]
默认情况下,它为您提供了季度的开始日期,因此我按here所述添加了偏移量.
点击查看更多相关文章
转载注明原文:python-熊猫将日期(季度)转换为日期时间对象 - 乐贴网