How to calculate average/mean of Pandas column?

Given a Pandas DataFrame, we have to calculate average or mean of column.
Submitted by Pranit Sharma, on May 27, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data.

The most fascinating key point about pandas is that it contains numerous amounts of function to calculate almost everything mathematically and logically.

With the help of pandas, we can calculate the mean of any column in a DataFrame, the column values should be an integer or float values and not a string.

Pandas.DataFrame[col].Mean()

Mean is nothing but an average value of a series of a number. Mathematically, the mean can be calculated as:

Here, x̄ is the mean, x is the summation of all the values and n is the total number of values/elements.

Suppose we have a series of numbers from 1 to 10, then the average of this series will be:

```∑x = 1+2+3+4+5+6+7+8+9+10
∑x = 55
n = 10
x̄ = 55/10
x̄ = 5.5
```

But in pandas, we use pandas.DataFrame['col'].mean() directly to calculate the average value of a column.

To work with pandas, we need to import pandas package first, below is the syntax:

```import pandas as pd
```

Let us understand with the help of an example.

```# Import pandas Package
import pandas as pd

# Creating dictionary
d = {
'Age':[40, 33, 36, 36, 25, 38]
}

# Creating a Dataframe
df = pd.DataFrame(d,index = ['a', 'b', 'c', 'd', 'e', 'f'])

print("Created Dataframe:\n", df,"\n")
```

Output:

Now, calculate the average age of this DataFrame -

```# Calculating average age
result = df['Age'].mean()

# Display result
print("Average age in CSK:\n",result)
```

Output:

Preparation

What's New

Top Interview Coding Problems/Challenges!