ADVERTISEMENT
ADVERTISEMENT

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:

Average/Mean Formua

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 = {
    'CSK':['Dhoni', 'Jadeja', 'Raydu','Uthappa', 'Gaiakwad', 'Bravo'],
    '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:

Example 1: Calculate average/mean

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:

Example 2: Calculate average/mean

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.