【问题标题】:segmentation total based on multiple condition基于多个条件的分割总数
【发布时间】:2020-08-09 21:52:23
【问题描述】:

数据框:-

ID spend month_diff    
12  10    -1         
12  10    -2         
12  20     1        
12  30     2         
13  15    -1         
13  20    -2        
13  25     1        
13  30     2        

我想根据特定 ID 的月差来获取支出总计。负数表示客户去年的支出,正数表示今年。所以,我想比较客户过去一年和今年的支出。所以条件如下:

条件:-

if month_diff >= -2 and < 0 then cumulative spend for negative months - flag=pre
if month_diff > 0 and <=2 then  cumulative spend for positive months  - flag=post

所需的数据框:-

ID spend month_diff tot_spend   flag    
12  10    -2         20         pre
12  30     2         50         post
13  20    -2         35         pre
13  30     2         55         post

【问题讨论】:

    标签: pandas dataframe segment


    【解决方案1】:

    numpy.signSeries.shiftSeries.neSeries.cumsum 一起用于连续组,并通过聚合GroupBy.lastsum 传递给DataFrame.groupby

    最后使用numpy.select

    a = np.sign(df['month_diff'])
    g = a.ne(a.shift()).cumsum()
    df1 = (df.groupby(['ID', g])
             .agg({'month_diff':'last', 'spend':'sum'})
             .reset_index(level=1, drop=True)
             .reset_index())
    df1['flag'] = np.select([df1['month_diff'].ge(-2) & df1['month_diff'].lt(0),
                             df1['month_diff'].gt(0) & df1['month_diff'].le(2)], 
                             ['pre','post'], default='another val')
    print (df1)
       ID  month_diff  spend  flag
    0  12          -2     20   pre
    1  12           2     50  post
    2  13          -2     35   pre
    3  13           2     55  post
    

    【讨论】:

    • 如果没有,您也可以告诉我。正负月差中的行数不相等(即 2 -ve 个月但 6 +ve 个月。您的解决方案工作得非常好,但如果我想将 2 个月的负数支出和 4 个月的正数支出总和 month_diff .如何根据月数控制支出累积。谢谢
    • @Karan - 是否可以使用这些新数据和预期输出发布新问题?
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多