Home > Software design >  adding column total and mean to DataFrame
adding column total and mean to DataFrame

Time:09-30

I have a data frame like below, I want the sum of col1 and the average of col2 and col3 in the last row.

col1   col2  col3
 1      3    1
 3      4    1
 3      5    2
 1      1    3
 2      2    4
 3      1    9
 2      3    5
 2      5    6

total 17.0    3.0   3.8

Please help.

CodePudding user response:

Use DataFrame.agg with DataFrame.loc:

.agg function will aggregate the data and it can aggregate for sum, mean in one call.

.loc will add a new row with given index.

df.loc['new'] = df.agg({'col1':'sum', 'col2':'mean', 'col3':'mean'})
print (df)
     col1  col2   col3
0     1.0   3.0  1.000
1     3.0   4.0  1.000
2     3.0   5.0  2.000
3     1.0   1.0  3.000
4     2.0   2.0  4.000
5     3.0   1.0  9.000
6     2.0   3.0  5.000
7     2.0   5.0  6.000
new  17.0   3.0  3.875

CodePudding user response:

df.loc['new'] = df.agg({'col1':'sum', 'col2':'mean', 'col3':'mean'}) print (df)

  • Related