How to Calculate Mean in Python Pandas ?

Spread the love

To calculate mean in pandas, we use the dataframe’s mean() method. In statistics, the mean or average is the sum of the all the values in a set divided by the total number of items in the set.

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 Mean of the Columns –

By default, the mean() method calculate the mean of the columns.

You can calculate the mean of a single column like this –

df['Apple'].mean()
#output
116.16666666666667

Or you can calculate the mean of multiple numeric columns at once like this.

df.mean()
#output
Apple     116.166667
Orange     63.250000
Banana     27.750000
Mango     114.583333
dtype: float64

2 . Calculate the Mean of the rows –

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

df.mean(axis=1)
#output
Jan      60.25
Feb      61.25
Mar      65.00
Apr      81.25
May      89.00
June     76.00
Jul     100.75
Aug     104.75
Sep      84.50
Oct      86.00
Nov      73.75
Dec      82.75
dtype: float64

Rating: 1 out of 5.

Leave a Reply