A Detailed Guide to the Python mean() Method With Examples

Hey, folks! In this article, we will be focusing on Python mean() function in order to perform the mean operation.

Mean is the value that represents an entire set of entities. It is considered as the central value of a set of numbers.

Mean is calculated by dividing the summation of all the entity values by the number of entities. Essentially, the mean is the average of the specified values.


(sum of values)/total values

Now, let us understand the working of the mean() function to calculate the mean.

Using the Python mean() function

The mean() function helps in calculating the mean of a set of values passed to the function.

Python statistics module is used to perform all the statistical operations on the data. We need to import the statistics module using the below command:

Syntax: Importing the statistics module

The statistics.mean() function accepts the data values as argument and returns the mean of the values passed to it.




Python mean() function with NumPy module

Python NumPy module represents the set of values in the form of an array. We can calculate the mean of these array elements using numpy.mean() function.

The numpy.mean() function performs the same way as of the statistics.mean() function.



In the above example, we have used the numpy.arange(start,stop) function to generate evenly spaced values in the range provided as parameters. Further, numpy.mean() function is used to calculate the mean of all the array elements.


Python mean() function with Pandas module

Python Pandas module deals with huge datasets in the form of DataFrames. The mean of those huge data sets can be calculated by using pandas.DataFrame.mean() function.

The pandas.DataFrame.mean() function returns the mean of those data values.


Example 1:

In the above example, we have created a NumPy array using numpy.arange() function and then converted the array values into a DataFrame using pandas.DataFrame() function. Further, we have calculated the mean of the DataFrame values using pandas.DataFrame.mean() function.


Example 2:

Input Dataset:

MTCARS Dataset

MTCARS Dataset

In the above example, we have used the above mentioned dataset, and calculated the mean of all the data values present in the data column ‘qsec‘.



Thus, in this article, we have understood the working of Python mean() function along with NumPy and Pandas module.


Python mean() function — Official Documentation

By admin

Leave a Reply

%d bloggers like this: