python - Groupby 多列和 Sum - 创建新列并添加 If 条件

标签 python pandas group-by sum pandas-groupby

我需要对多列进行分组,然后在添加了 If 条件的新列中获取总和。我尝试了下一个代码,它非常适合按单列分组:

df['new column'] = (
    df['value'].where(df['value'] > 0).groupby(df['column1']).transform('sum')
)

但是,当我尝试按多列分组时出现错误。

df['new_column'] = (
        df['value'].where(df['value'] > 0).groupby(df['column1', 'column2']).transform('sum')
    )

错误:

->return self._engine.get_loc(casted_key) 
The above exception was the direct cause of the following exception: 
->indexer = self.columns.get_loc(key) 
->raise KeyError(key) from err 
->if is_scalar(key) and isna(key) and not self.hasnans: ('column1', 'column2')

您能否建议我应该如何更改代码以获得相同的结果但按多列分组?

谢谢

最佳答案

错误原因

  • 选择多列的语法 df['column1', 'column2'] 是错误的。这应该是 df[['column1', 'column2']]
  • 即使您使用 df[['column1', 'column2']] 作为 groupby,pandas 也会引发另一个错误,提示石斑鱼应该是 一维。这是因为 df[['column1', 'column2']] 返回一个数据框,它是一个二维对象。

如何修复错误?

困难的方式:

将每个分组列作为一维系列传递给 groupby

df['new_column'] = (
        df['value']
          .where(df['value'] > 0)
          .groupby([df['column1'], df['column2']]) # Notice the change
          .transform('sum')
)
简单方法:

首先将屏蔽的列值分配给目标列,然后像往常一样执行groupby + transform

df['new_column'] = df['value'].where(df['value'] > 0)
df['new_column'] = df.groupby(['column1', 'column2'])['new_column'].transform('sum')

关于python - Groupby 多列和 Sum - 创建新列并添加 If 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72246392/

相关文章:

python - 在 Django 中获取模型的属性类型

python - Pandas 日复一日

python - Pandas 设置元素样式依赖于另一个带有多重索引的数据框

python - 如何添加复制某些列的新行,但在其他列中分配新值

MySQL(Workbench)按大数据集(30GB)上的操作进行分组

python - 如何连接 pandas.read_html 的结果列表

Python:一个列表中的子集元素基于另一个列表中的子字符串,每个子字符串仅保留一个元素

python - 面临属性错误: for 'tag_' using Spacy in Python

python - 将 PyArrow Parquet 加速到 Pandas 以获取具有大量字符串的数据帧

mysql - 如果任何值为 NULL,GROUP_CONCAT 返回 NULL