+3 votes
in Programming Languages by (60.0k points)
I want to find the sum of all row values for all columns of a pandas dataframe. Which function should I use for it?

E.g.

A B

1 3

2 4

3 5

The result should be:

A 6

B 12

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use the sum() function of the pandas dataframe. This function returns the sum of the values along the given axis.

If you want to sum all row values for all columns, you can use axis=0 as the argument.

If you want to sum all column values for all rows, you can use axis=1 as the argument.

Here is an example:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'A':np.random.random(10), 'B':np.random.random(10)})
>>> df
          A         B
0  0.970108  0.164693
1  0.327336  0.864824
2  0.162746  0.152914
3  0.148267  0.533964
4  0.648864  0.507339
5  0.148589  0.520032
6  0.850769  0.265669
7  0.566881  0.996158
8  0.369867  0.278782
9  0.772552  0.979034
 

>>> df.sum(axis=0)
A    4.965979
B    5.263410
dtype: float64

>>> df.sum(axis=1)
0    1.134801
1    1.192160
2    0.315660
3    0.682231
4    1.156203
5    0.668621
6    1.116438
7    1.563039
8    0.648649
9    1.751586
dtype: float64
>>>
 


...