Skip to content
Advertisement

how to add new row into each group of groupby in PANDAS , one of the value of that row is sum of values of each groups

let’s say I have a data frame like this

JavaScript

I wanted to add a new row into each group of groupby(by=[‘eff_date’,’mdl_cd’,’ast_cd’]) in which column value for eff_date,mdl_cd and ast_cd will remain same but for prop_cd value become Hlds and value value column become sum of value of that group e.g. for first group value of value column will be (-0.1234+0.5123+-0.7612) i.e. -0.3723

hence the output will be like this

JavaScript

how to perform this computation using pandas

Advertisement

Answer

You can create a dataframe with the sum of each group by .groupby() and .sum(), set the prop_cd as Hlds by .assign().

Then, concat with the original dataframe by pd.concat() and sort the columns to put the sum rows back together with their respective groups by .sort_values(), as follows:

JavaScript

Result:

JavaScript

Setup

JavaScript

Interim result:

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