Mean Function in Python pandas (Dataframe, Row and column wise mean)

mean() – Mean Function in python pandas is used to calculate the arithmetic mean of a given set of numbers, mean of a data frame ,mean of column and mean of rows , lets see an example of each . We need to use the package name “statistics” in calculation of mean. In this tutorial we will learn,

  • How to find the mean of a given set of numbers
  • How to find mean of a dataframe
  • How to find the mean of a column in dataframe
  • How to find row mean of a dataframe

Mean Function in Python

Simple mean function is shown below

# calculate arithmetic mean
Import statistics

print(statistics.mean([1,9,5,6,6,7]))
print(statistics.mean([4,-11,-5,16,5,7]))

output:

5.66666666667
2.66666666667

 

Mean of a dataframe:

Create dataframe

import pandas as pd
import numpy as np

#Create a DataFrame
d = {
    'Name':['Alisa','Bobby','Cathrine','Madonna','Rocky','Sebastian','Jaqluine',
   'Rahul','David','Andrew','Ajay','Teresa'],
   'Score1':[62,47,55,74,31,77,85,63,42,32,71,57],
   'Score2':[89,87,67,55,47,72,76,79,44,92,99,69]}


df = pd.DataFrame(d)
df

So the resultant dataframe will be

mean function in python pandas

Mean of the dataframe:


# mean of the dataframe
df.mean()

it will calculate the mean of the dataframe across columns so the output will be

Score1  58.0
Score2  73.0
dtype:  float64

 

Column Mean of the dataframe:


# column mean of the dataframe
df.mean(axis=0)

axis=0 argument calculates the column wise mean of the dataframe so the result will be

Score1 58.0
Score2 73.0
dtype: float64

 

Row Mean of the dataframe:


# Row mean of the dataframe
df.mean(axis=1)

axis=1 argument calculates the row wise mean of the dataframe so the result will be

0   75.5
1   67.0
2   61.0
3   64.5
4   39.0
5   74.5
6   80.5
7   71.0
8   43.0
9   62.0
10   85.0
11   63.0
dtype: float64

 

Calculate the mean of the specific Column


# mean of the specific column
df.loc[:,"Score1"].mean()

the above code calculates the mean of the “Score1” column so the result will be

58.0

 

previous-small mean function in python                                                                                                                next_small mean function in python