pandas 将日期(季度)转换为日期时间对象 [英] pandas convert date (quarters) to datetime object

查看:107
本文介绍了 pandas 将日期(季度)转换为日期时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫DataFrame,它的列(标题)需要解析为datetime对象,以便可以将其转换为时间序列.

I have a pandas DataFrame that has a column (Title) that needs to be parsed as a datetime object so I can turn this into a time series.

    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

谁能指出最好的方法是什么?

can anyone point out what would be the best approach to this?

我想要的输出将是

    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

推荐答案

如果年"和季度"之间没有空格,大熊猫可以对其进行解析,因此您需要替换空格字符:

If there is no space between the Year and the Quarter, pandas can parse it so you need to replace the space character:

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]

默认情况下,它为您提供了季度的开始日期,因此我按照

By default it gives you the start date of the quarter so I added an offset as described here.

这篇关于 pandas 将日期(季度)转换为日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆