我需要按多个列分组&然后在添加了If条件的新列中求和.我try 了下一个代码,它通过单列分组非常有效:

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

然而,当我try 按多个列进行分组时,我得到了一个错误.

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')

您能告诉我应该如何更改代码以获得相同的结果,但按多个列分组吗?

非常感谢.

推荐答案

Cause of error

  • Select 多个列df['column1', 'column2']的语法错误.这应该是df[['column1', 'column2']]
  • 即使你用df[['column1', 'column2']]表示groupby,Pandas 也会提出另一个错误,抱怨石斑鱼应该是one dimensional.这是因为df[['column1', 'column2']]返回的数据帧是二维对象.

How to fix the error?

Hard way:

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

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

首先将屏蔽列的值指定给目标列,然后像通常那样执行groupby+transform

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

Python相关问答推荐

Python在tuple上操作不会通过整个单词匹配

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

时间序列分解

Gekko:Spring-Mass系统的参数识别

图像 pyramid .难以创建所需的合成图像

在极中解析带有数字和SI前缀的字符串

跳过嵌套JSON中的级别并转换为Pandas Rame

为什么'if x is None:pass'比'x is None'单独使用更快?

在matplotlib中使用不同大小的标记顶部添加批注

Pandas:填充行并删除重复项,但保留不同的值

Polars map_使用多处理对UDF进行批处理

Pandas在rame中在组内洗牌行,保持相对组的顺序不变,

如何使用pytest在traceback中找到特定的异常

按条件计算将记录拆分成两条记录

Matplotlib中的曲线箭头样式

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

Django更新视图未更新

具有不同坐标的tkinter canvs.cocords()和canvs.moveto()

为什么这个正则表达式没有捕获最后一次输入?

Django REST框架+Django Channel->;[Errno 111]连接调用失败(';127.0.0.1';,6379)