Search code examples
pandasdataframegroup

Sum column values within the same group and save that dataframe separately


Let's say I have a dataframe that looks like the following:

In [186]:

df = pd.read_csv(file, engine='python',sep='\t')
df

Out[186]:
length value   parent
        
100       5       X
 90      18       X
 77      17       Y
 15      15       Y
 89      11       Z

What do I do if I want to change this datframe into the following:

value   parent
        
  23    X
  32    Y
  11    Z

I am basically summing up the column values within the same group and saving that dataframe into a separate data frame. As you can see, I am not intested in the length column.


Solution

  • drop the length column and do

    df.groupby(['parent']).sum()
    

    documentation