【问题标题】:Pandas: Add data for missing monthsPandas:添加缺失月份的数据
【发布时间】:2013-06-24 23:43:30
【问题描述】:

我有一个按月按客户划分的销售信息数据框,看起来像这样,有多个客户和不同的月周期和支出:

      customer_id month_year      sales
   0        12    2012-05          2.58   
   1        12    2011-07         33.14  
   2        12    2011-11        182.06   
   3        12    2012-03        155.32   
   4        12    2012-01         71.24 

如您所见,对于每个客户来说,很多月份都丢失了。我想为 month_year 范围内的所有月份为每个客户添加额外的行,销售额 = 0.0。

谁能建议最好的方法?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    类似这样的东西;请注意,没有定义填充 customer_id(因为您可能在 groupby 或其他东西中有这个)。

    最后你可能需要reset_index(如果需要)

    In [130]: df2 = df.set_index('month_year')
    
    In [131]: df2 = df2.sort_index()
    
    In [132]: df2
    Out[132]: 
                customer_id   sales
    month_year                     
    2011-07              12   33.14
    2011-11              12  182.06
    2012-01              12   71.24
    2012-03              12  155.32
    2012-05              12    2.58
    
    In [133]: df2.reindex(pd.period_range(df2.index[0],df2.index[-1],freq='M'))
    Out[133]: 
             customer_id   sales
    2011-07           12   33.14
    2011-08          NaN     NaN
    2011-09          NaN     NaN
    2011-10          NaN     NaN
    2011-11           12  182.06
    2011-12          NaN     NaN
    2012-01           12   71.24
    2012-02          NaN     NaN
    2012-03           12  155.32
    2012-04          NaN     NaN
    2012-05           12    2.58
    
    In [135]: df2['customer_id'] = 12
    
    In [136]: df2.fillna(0.0)
    Out[136]: 
             customer_id   sales
    2011-07           12   33.14
    2011-08           12    0.00
    2011-09           12    0.00
    2011-10           12    0.00
    2011-11           12  182.06
    2011-12           12    0.00
    2012-01           12   71.24
    2012-02           12    0.00
    2012-03           12  155.32
    2012-04           12    0.00
    2012-05           12    2.58
    

    【讨论】:

    • 此答案假设只有一个客户 (customer_id=12)。如果有多个客户,您希望按customer_idmonth_year 进行排序呢?
    【解决方案2】:

    我找到了一种不同的方式来填充缺失的月份(它们将用 NaN 填充),同时还考虑了多个可能的客户。

    df = df.set_index(['month_year', 'customer_id'])['sales'].unstack().unstack().reset_index()
    df = df.rename(columns={0:'sales'})
    

    虽然这绝对不雅,但它完成了工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 2022-11-25
      • 2017-10-04
      相关资源
      最近更新 更多