pandas 群体总和 [英] Pandas groupby sum

查看:126
本文介绍了 pandas 群体总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框如下:

  ref,类型,金额
001,foo,10
001,foo,5
001,bar,50
001,bar,5
001,测试,100
001,测试,90
002,foo ,20
002,foo,35
002,bar,75
002,bar,80
002,test,150
002,test,110

这就是我想要得到的:



<$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' 190
001,bar,50,15,55,190
001,bar,5,15,55,190
001,test,100,15,55,190
001,test,90,15,55,190
002,foo,20,55,155,260
002,foo,35,55,155,260
002,bar,75 ,55,155,260
002,bar,80,55,155,260
002,测试,150,55,155,260
002,测试,110,55,155,155, 260

所以我有这个:

 df.groupby('ref')['amount']。transform(sum)

但是我怎样才能过滤它上述仅适用于 type = foo bar test

解决方案

使用数据透视表

 >>> ; b = pd.pivot_table(df,values ='amount',index = ['ref'],columns = ['type'],aggfunc = np.sum)
>>> b
type bar foo test
ref
1 55 15 190
2 155 55 260

>>> pd.merge(df,b,left_on ='ref',right_index = True)
ref类型数量bar foo测试
0 1 foo 10 55 15 190
1 1 foo 5 55 15 190
2 1 bar 50 55 15 190
3 1 bar 5 55 15 190
4 1测试100 55 15 190
5 1测试90 55 15 190
6 2 foo 20 155 55 260
7 2 foo 35 155 55 260
8 2 bar 75 155 55 260
9 2 bar 80 155 55 260
10 2测试150 155 55 260
11 2 test 110 155 55 260


I have a dataframe as follows:

ref, type, amount
001, foo, 10
001, foo, 5
001, bar, 50
001, bar, 5
001, test, 100
001, test, 90
002, foo, 20
002, foo, 35
002, bar, 75
002, bar, 80
002, test, 150
002, test, 110

This is what I'm trying to get:

ref, type, amount, foo, bar, test
001, foo, 10, 15, 55, 190
001, foo, 5, 15, 55, 190
001, bar, 50, 15, 55, 190
001, bar, 5, 15, 55, 190
001, test, 100, 15, 55, 190
001, test, 90, 15, 55, 190
002, foo, 20, 55, 155, 260
002, foo, 35, 55, 155, 260
002, bar, 75, 55, 155, 260
002, bar, 80, 55, 155, 260
002, test, 150, 55, 155, 260
002, test, 110, 55, 155, 260

So I have this:

df.groupby('ref')['amount'].transform(sum)

But how can I filter it such that the above only applies to rows where type=foo or bar or test?

解决方案

A solution using pivot table :

>>> b = pd.pivot_table(df, values='amount', index=['ref'], columns=['type'], aggfunc=np.sum)
>>> b
type  bar  foo  test
ref
1      55   15   190
2     155   55   260

>>> pd.merge(df, b, left_on='ref', right_index=True)
    ref  type  amount  bar  foo  test
0     1   foo      10   55   15   190
1     1   foo       5   55   15   190
2     1   bar      50   55   15   190
3     1   bar       5   55   15   190
4     1  test     100   55   15   190
5     1  test      90   55   15   190
6     2   foo      20  155   55   260
7     2   foo      35  155   55   260
8     2   bar      75  155   55   260
9     2   bar      80  155   55   260
10    2  test     150  155   55   260
11    2  test     110  155   55   260

这篇关于 pandas 群体总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆