pandas 将datetimeindex格式转换为四分之一 [英] pandas format datetimeindex to quarters
问题描述
通过重新抽样工作,我将我的每月值转换为季度值:
With a resample job, I have my monthly values converted to quarterly values:
hs=hs.resample('QS',axis=1).mean()
效果很好,我的专栏看起来像这样:
Works well, my columns look like this:
hs.columns:
DatetimeIndex(['2000-01-01', '2000-04-01', '2000-07-01', '2000-10-01',
'2001-01-01', '2001-04-01', '2001-07-01', '2001-10-01',
'2002-01-01', '2002-04-01', '2002-07-01', '2002-10-01',
现在,我希望他们将其转换为YYYYq [1-4]格式,我认为该格式应尽可能简单(根据此
Now I want them to convert in the YYYYq[1-4] format, which I thought should be as easy as (according to this Link):
hs.columns.strftime('%Yq%q')
但这给出了:
array(['2000qq', '2000qq', '2000qq', '2000qq', '2001qq', '2001qq',
'2001qq', '2001qq', '2002qq', '2002qq', '2002qq', '2002qq',
'2003qq', '2003qq', '2003qq', '2003qq', '2004qq', '2004qq',
我在哪里出错了,我该如何解决?
Where do I go wrong and how can i fix this?
推荐答案
文档在 Period 数据类型而非 Datetime 数据类型上指定了strftime
;要使用%q
格式程序,可以将datetime索引转换为Period(天数为单位),然后对其进行格式化:
The documentation specifies strftime
on Period data type not Datetime data type; To use %q
formatter, you can convert the datetime Index to Period (days as unit) and then format it:
cols = pd.DatetimeIndex(['2000-01-01', '2000-04-01', '2000-07-01', '2000-10-01',
'2001-01-01', '2001-04-01', '2001-07-01', '2001-10-01',
'2002-01-01', '2002-04-01', '2002-07-01', '2002-10-01'])
cols.to_period('D').strftime('%Yq%q')
# hs.columns.to_period('D').strftime('%Yq%q')
#array([u'2000q1', u'2000q2', u'2000q3', u'2000q4', u'2001q1', u'2001q2',
# u'2001q3', u'2001q4', u'2002q1', u'2002q2', u'2002q3', u'2002q4'],
# dtype='<U6')
或者仅将to_period
与Q
(四分之一)作为单位使用:
Or simply use to_period
with Q
(quarter) as unit:
cols.to_period('Q')
# hs.columns.to_period('Q')
#PeriodIndex(['2000Q1', '2000Q2', '2000Q3', '2000Q4', '2001Q1', '2001Q2',
# '2001Q3', '2001Q4', '2002Q1', '2002Q2', '2002Q3', '2002Q4'],
# dtype='period[Q-DEC]', freq='Q-DEC')
这篇关于 pandas 将datetimeindex格式转换为四分之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!