How can I "merge" rows by same value in a column in Pandas with aggregation functions?
You are looking for
aggregation_functions = {'price': 'sum', 'amount': 'sum', 'name': 'first'}
df_new = df.groupby(df['id']).aggregate(aggregation_functions)
which gives
price name amount
id
1 130 anna 3
2 42 bob 30
3 3 charlie 110
For same columns ordering is necessary add reindex
, because aggregate by dict
:
d = {'price': 'sum', 'name': 'first', 'amount': 'sum'}
df_new = df.groupby('id', as_index=False).aggregate(d).reindex(columns=df.columns)
print (df_new)
amount id name price
0 3 1 anna 130
1 30 2 bob 42
2 110 3 charlie 3