Pandas DataFrame sum() method with examples

Spread the love

The sum() method in pandas calculates the sum of the values over the requested axis. This is equivalent to the method numpy.sum.

Examples –

Let’s create a dataset to work with.

import pandas as pd

data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
       'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
       'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
       'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}

index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

1 . Calculate the Sum of the Columns –

You can calculate the sum of a single column like this

df['Apple'].sum()
#output
1394

or you can calculate the sum for all the columns like this

df.sum()
#output
Apple     1394
Orange     759
Banana     333
Mango     1375
dtype: int64

2 . Calculate the Sum of the Rows –

To calculate the sum of each rows, we need to set the axis parameter to axis=1 or columns.

df.sum(axis=1)
#output
Jan     241
Feb     245
Mar     260
Apr     325
May     356
June    304
Jul     403
Aug     419
Sep     338
Oct     344
Nov     295
Dec     331
dtype: int64

Rating: 1 out of 5.

Leave a Reply