【发布时间】:2017-09-19 17:44:01
【问题描述】:
我的 df 看起来像这样:
Total
language Julia Python R SQLite
date
2015-03-01 NaN NaN 17.0 NaN
2015-04-01 NaN 156.0 189.0 NaN
2015-05-01 13.0 212.0 202.0 NaN
该指数是按月计算的,我希望它是按季度计算的:
df.resample("Q").sum()
给我这个:
Total
language Julia Python R SQLite
date
2015-03-31 NaN NaN 17.0 NaN
2015-06-30 22.0 677.0 594.0 26.0
2015-09-30 37.0 1410.0 1250.0 146.0
但我想显示这样的索引Start month - End month 2017 而不是结束日期。所需的df:
Total
language Julia Python R SQLite
Jan - Mar, 2015 NaN NaN 17.0 NaN
Apr - Jun, 2015 22.0 677.0 594.0 26.0
Jul - Sep, 2015 37.0 1410.0 1250.0 146.0
有熊猫的方法吗?我是这样做的,但它很脏,我相信有更好的方法来做到这一点(文档中的 resample 方法在示例中缺乏......):
def quarterlyMonthNmaes(x):
start_date = x.name - pd.offsets.MonthBegin(3)
final_date = str(start_date.strftime('%b')) + " - " + str(x.name.strftime('%b, %Y'))
return final_date
df["Total"].apply(quarterlyMonthNmaes, axis=1)
【问题讨论】: