我需要按多列进行分组,然后在新列中添加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')
请问如何更改代码以获得相同结果但按多列分组?
谢谢