按照某一列的分类值对多列进行分组,并计算各组的总和(Pandas)

huangapple go评论108阅读模式
英文:

Groupby several columns and take the sum based off of categorical values within a column (Pandas)

问题

我正在寻找根据某一列中的分类值对多列进行分组并求和的方法。

数据

  1. 姓名 大小 类型
  2. AA 9385 FALSE
  3. AA 9460 FALSE
  4. AA 9572 TRUE
  5. AA 9680
  6. BB 10 TRUE
  7. BB 10 TRUE
  8. BB 20 FALSE
  9. BB 20 FALSE

期望的结果

  1. 姓名 大小 类型
  2. AA 9572 TRUE
  3. AA 18845 FALSE
  4. AA 9680
  5. BB 20 TRUE
  6. BB 40 FALSE
  7. BB

正在执行的操作

  1. df = df.groupby('name').agg({'size': 'sum', 'type': lambda x: x.value_counts().idxmax()})

然而,这似乎已经移除了空值。有任何建议吗?

英文:

I am looking to groupby several columns and take the sum based off of categorical values within a column.

Data

  1. name size type
  2. AA 9385 FALSE
  3. AA 9460 FALSE
  4. AA 9572 TRUE
  5. AA 9680
  6. BB 10 TRUE
  7. BB 10 TRUE
  8. BB 20 FALSE
  9. BB 20 FALSE

Desired

  1. name size type
  2. AA 9572 TRUE
  3. AA 18845 FALSE
  4. AA 9680
  5. BB 20 TRUE
  6. BB 40 FALSE
  7. BB

Doing

  1. df = df.groupby('name').agg({'size': 'sum', 'type': lambda x: x.value_counts().idxmax()})

However, this appears to have removed Null values. Any suggestion is appreciated.

答案1

得分: 1

使用dropna=False在groupby中:

  1. df.groupby(['name', 'type'], dropna=False, as_index=False)['size'].sum()

输出:

  1. name type size
  2. 0 AA False 18845
  3. 1 AA True 9572
  4. 2 AA NaN 9680
  5. 3 BB False 40
  6. 4 BB True 20
英文:

Use dropna=False in groupby:

  1. df.groupby(['name', 'type'], dropna=False, as_index=False)['size'].sum()

Output:

  1. name type size
  2. 0 AA False 18845
  3. 1 AA True 9572
  4. 2 AA NaN 9680
  5. 3 BB False 40
  6. 4 BB True 20

huangapple
  • 本文由 发表于 2023年6月6日 07:01:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定