读取 pandas 中的季度数据
reading quarterly data in pandas
我有一个季度观察数据集,表示为 200101(2001 年第 1 季度)到 201504(2015 年第 4 季度)。我想将它们转换为适当的 pandas 日期索引。
200101 -> 2001-03-31
...
201504 -> 2015-12-31
对于year/months我经常用
import datetime as dt
dates = [dt.datetime.strptime(str(d), '%Y%m') for d in series['date']]
series['date'] = pd.date_range(dates[0], dates[-1], freq='M')
很遗憾,'%Y%q' 符号是不允许的。关于如何优雅地阅读季度日期有什么建议吗?
您可以将这些字符串转换为 PeriodIndex(freq='Q')
,然后(如果需要)转换为 timestamp(freq='M')
演示:
In [272]: df
Out[272]:
qt
0 200101
1 201504
In [273]: pd.PeriodIndex(df.qt.astype(str).str.replace(r'(\d{4})[0]?(\d{1})', r'q'),
freq='Q') \
.to_timestamp(freq='M')
Out[273]: DatetimeIndex(['2001-01-31', '2015-10-31'], dtype='datetime64[ns]', name='qt', freq=None)
我有一个季度观察数据集,表示为 200101(2001 年第 1 季度)到 201504(2015 年第 4 季度)。我想将它们转换为适当的 pandas 日期索引。
200101 -> 2001-03-31
...
201504 -> 2015-12-31
对于year/months我经常用
import datetime as dt
dates = [dt.datetime.strptime(str(d), '%Y%m') for d in series['date']]
series['date'] = pd.date_range(dates[0], dates[-1], freq='M')
很遗憾,'%Y%q' 符号是不允许的。关于如何优雅地阅读季度日期有什么建议吗?
您可以将这些字符串转换为 PeriodIndex(freq='Q')
,然后(如果需要)转换为 timestamp(freq='M')
演示:
In [272]: df
Out[272]:
qt
0 200101
1 201504
In [273]: pd.PeriodIndex(df.qt.astype(str).str.replace(r'(\d{4})[0]?(\d{1})', r'q'),
freq='Q') \
.to_timestamp(freq='M')
Out[273]: DatetimeIndex(['2001-01-31', '2015-10-31'], dtype='datetime64[ns]', name='qt', freq=None)