我使用以下代码,我的目标是按2列分组(在其中的几十列中),然后保留所有其他列的第一个值,同时将另外两个列的值相加。不管我尝试了什么组合,它都不起作用。
所用代码:
df1 = df.groupby(['col_1', 'Col_2'], as_index = False)[['Age', 'Income']].apply(sum).first()我所得到的错误如下所示,这使我相信这可以通过我使用的代码的一个稍微不同的版本来完成。
TypeError: first() missing 1 required positional argument: 'offset'任何建议都将不胜感激!
发布于 2022-05-16 21:16:07
您可以使用agg为每一列配置相应的函数。
group = ['col_1', 'col_2']
(df.groupby(group, as_index=False)
.agg({
**{x: 'first' for x in df.columns[~df.columns.isin(group)]}, # for all columns other than grouping column
**{'Age': 'sum', 'Income': 'sum'} # Overwrite aggregation for specific columns
})
)此部分{ **{...}, **{...} }将生成
{
'Age': 'sum',
'Income': 'sum',
'othercol': 'first',
'morecol': 'first'
}https://stackoverflow.com/questions/72265185
复制相似问题