I have a DataFrame with numerical values. What is the simplest way of appending a row (with a given index value) that represents the sum of each column?
To get the total or sum of a column use sum() method, and to add the result of the sum as a row to the DataFrame use loc[] , at[] , append() and pandas. Series() methods.
sum() function is used to return the sum of the values for the requested axis by the user. If the input value is an index axis, then it will add all the values in a column and works same for all the columns. It returns a series that contains the sum of all the values in each column.
To add a Total
column which is the sum across the row:
df['Total'] = df.sum(axis=1)
To add a row with column-totals:
df.loc['Total']= df.sum()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With