【问题标题】:Python DataFrame sum values in columnA based on conditions in columnsNPython DataFrame 根据列中的条件对列中的值求和
【发布时间】:2017-06-20 07:11:43
【问题描述】:

我有一组不同类型的账户,有不同的选项,我试图计算每个用户在 2016 年每个月的储蓄与他们在 2014 年和 2015 年使用的平均金额的比较。我的 DataFrame 如下所示:

key amount  id  month   opt type    year
0   100     5   1       M   E       2014
1   200     5   1       M   G       2014
2   300     5   1       R   E       2014
3   400     5   1       R   G       2014
4   105     5   1       M   E       2015
5   205     5   1       M   G       2015
6   305     5   1       R   G       2015
7   405     5   1       R   E       2015
8   90      5   1       M   E       2016
9   180     5   1       M   G       2016
10  310     5   1       R   G       2016
11  350     5   1       R   E       2016

基于上述情况,我预计用户“5”在 2016 年第 1 个月为“类型”“E”和选项“M”节省了 12.5,而他们在 2015 年的平均“amt”为 102.5,并且2016 年。

我对 2016 年第 1 个月各种类型的完整答案如下:

M|E -12.5
M|G -22.5
R|E  -2.5
R|G -42.5

我认为 groupby() 函数可能适用于此,但我开发的公式并没有给我正确的答案。

df_savings = df.groupby(['id','year','month','type','opt'], group_keys=False).apply(
         lambda s: float(s['amount'][s.year < 2016].sum()/float(2)) - float(s['amount'][s.year == 2016].sum()))

任何帮助将不胜感激。这是用于上述示例 df 的代码:

df = pd.DataFrame({'id':[5,5,5,5,5,5,5,5,5,5,5,5],
               'type':['E','G','E','G','E','G','G','E','E','G','G','E'],
               'opt':['M','M','R','R','M','M','R','R','M','M','R','R'],
            'year':[2014,2014,2014,2014,2015,2015,2015,2015,2016,2016,2016,2016],
            'month':[1,1,1,1,1,1,1,1,1,1,1,1],
            'amount':[100,200,300,400,105,205,305,405,90,180,310,350]
            })

【问题讨论】:

    标签: python pandas dataframe sum conditional


    【解决方案1】:

    你可以把它分成两部分,2016 年和 2014-15 年,然后 groupby 会产生两个相似的数据帧,你可以减去:

    df[df.year == 2016].groupby(['id', 'month', 'opt', 'type'])['amount'].sum() - df[df.year < 2016].groupby(['id', 'month', 'opt', 'type'])['amount'].mean()
    

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 2021-05-12
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多