Python DataFrame 根据列中的条件对列中的值求和
Python DataFrame sum values in columnA based on conditions in columnsN
我有一组不同类型的账户,有不同的选项,我正在尝试计算每个用户在 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 个月为 'type' 'E' 节省了 12.5 与他们的平均值相比选项 'M' 'amt' 2015 年和 2016 年的 102.5。
我预计 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]
})
你可以把它分成两部分,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()
我有一组不同类型的账户,有不同的选项,我正在尝试计算每个用户在 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 个月为 'type' 'E' 节省了 12.5 与他们的平均值相比选项 'M' 'amt' 2015 年和 2016 年的 102.5。
我预计 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]
})
你可以把它分成两部分,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()