Search code examples
pythonpandassum

Doing Sum and Mean on different columns to generate a grand total in pandas


I have a dataframe, something like

name perc score
a    0.2   40
b    0.4   89
c    0.3   90

I want to have a total row where 'perc' has a mean aggregation and 'score' has a sum aggregation. The output should be like

  name perc score
    a    0.2   40
    b    0.4   89
    c    0.3   90
  total  0.3  219

I want it as a dataframe output as I need to build plots using this. For now, I tried doing

df.loc['total'] = df.sum()

but this provides the sum for the percentage column as well, whereas I want an average for the percentage. How to do this in pandas?


Solution

  • try this:

    df.loc['total'] = [df['perc'].mean(), df['score'].sum()]
    

    Output:

           perc  score
    name              
    a      0.20   40.0
    b      0.40   89.0
    c      0.30   90.0
    total  0.30  219.0