【问题标题】:Pandas resample to quarterly with showing start and end monthPandas 重新采样到季度并显示开始和结束月份
【发布时间】: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) 

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用periods:

    idx = df.index.to_period('Q')
    df.index = ['{0[0]}-{0[1]}'.format(x) for x in zip(idx.asfreq('M', 's').strftime('%b'), 
                                                       idx.asfreq('M', 'e').strftime('%b %Y'))]
    print (df)
    
                  Total
                  language   Julia  Python      R  SQLite
    Jan-Mar 2015       NaN     NaN    17.0    NaN     NaN
    Apr-Jun 2015      22.0   677.0   594.0   26.0     NaN
    Jul-Sep 2015      37.0  1410.0  1250.0  146.0     NaN
    

    或者更简单:

    idx2 = df.index.strftime('%b %Y')
    idx1 = (df.index - pd.offsets.MonthBegin(3)).strftime('%b')
    df.index = ['{0[0]}-{0[1]}'.format(x) for x in zip(idx1, idx2)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-25
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2020-09-29
      相关资源
      最近更新 更多