Skip to content
Advertisement

groupby weighted average and sum in pandas dataframe

I have a dataframe:

JavaScript

I need a sum of adjusted_lots , price which is weighted average , of price and adjusted_lots , grouped by all the other columns , ie. grouped by (contract, month , year and buys)

Similar solution on R was achieved by following code, using dplyr, however unable to do the same in pandas.

JavaScript

is the same possible by groupby or any other solution ?

Advertisement

Answer

EDIT: update aggregation so it works with recent version of pandas

To pass multiple functions to a groupby object, you need to pass a tuples with the aggregation functions and the column to which the function applies:

JavaScript

You can see more here:

and in a similar question here:

[1] : https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html#groupby-aggregation-with-relabeling

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement