【问题标题】:Groupby on condition and calculate sum of subgroupsGroupby on条件并计算子组的总和
【发布时间】:2017-09-12 13:31:41
【问题描述】:

这是我的数据:

import numpy as np 
import pandas as pd
z = pd.DataFrame({'a':[1,1,1,2,2,3,3],'b':[3,4,5,6,7,8,9], 'c':[10,11,12,13,14,15,16]})
z

    a   b   c
0   1   3   10
1   1   4   11
2   1   5   12
3   2   6   13
4   2   7   14
5   3   8   15
6   3   9   16

问题:

如何计算每个子组的不同元素?例如,对于每个组,我想提取列 'c' 中的任何元素,其在列 'b' 中的对应元素在 4 和 9 之间,并将它们全部相加。

这是我写的代码:(它运行但我无法得到正确的结果)

gbz = z.groupby('a')
# For displaying the groups:
gbz.apply(lambda x: print(x))


list = []

def f(x):
    list_new = []
    for row in range(0,len(x)):
        if (x.iloc[row,0] > 4 and x.iloc[row,0] < 9):
            list_new.append(x.iloc[row,1])
    list.append(sum(list_new))

results = gbz.apply(f)

输出结果应该是这样的:

    a   c
0   1   12
1   2   27
2   3   15

【问题讨论】:

  • 从阅读文档开始。 This comparison 使用 SQL 可能会对您有所帮助,即使您不知道 SQL 是什么。
  • @dangom,当然。谢谢。

标签: python pandas dataframe group-by pandas-groupby


【解决方案1】:

更改操作顺序可能是最简单的方法,并首先根据您的条件进行过滤 - 在groupby 之后不会更改。

z.query('4 < b < 9').groupby('a', as_index=False).c.sum()

产生

   a   c
0  1  12
1  2  27
2  3  15

【讨论】:

  • @cᴏʟᴅsᴘᴇᴇᴅ 啊我没看到他们想要a不在索引中,一秒钟。
  • 应该是z.query('4 &lt; b &lt; 9').groupby('a').c.sum() 不包括在内。 `
【解决方案2】:

使用

In [2379]: z[z.b.between(4, 9, inclusive=False)].groupby('a', as_index=False).c.sum()
Out[2379]:
   a   c
0  1  12
1  2  27
2  3  15

或者

In [2384]: z[(4 < z.b) & (z.b < 9)].groupby('a', as_index=False).c.sum()
Out[2384]:
   a   c
0  1  12
1  2  27
2  3  15

【讨论】:

  • Op 提到了组...我想知道在 groupby 之前和之后进行总和的输出是否存在差异。
【解决方案3】:

你也可以先groupby

z = z.groupby('a').apply(lambda x: x.loc[x['b']\
           .between(4, 9, inclusive=False), 'c'].sum()).reset_index(name='c')
z

   a   c
0  1  12
1  2  27
2  3  15

【讨论】:

    【解决方案4】:

    或者你可以使用

    z.groupby('a').apply(lambda x : sum(x.loc[(x['b']>4)&(x['b']<9),'c']))\
                 .reset_index(name='c')
    Out[775]: 
       a   c
    0  1  12
    1  2  27
    2  3  15
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 2019-08-11
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      相关资源
      最近更新 更多