# Pandas DataFrame mean() Method

Rate this post

## Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

• The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt (\$), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (\$). Your terminal prompt may be different.

\$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

\$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.

Feel free to view the PyCharm installation guide for the required libraries.

Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np

## DataFrame mean()

The mean() method returns the average of the DataFrame/Series across a requested axis. If a DataFrame is used, the results will return a Series. If a Series is used, the result will return a single number (float).

The following methods can accomplish this task:

• The DataFrame.mean() method, or
•  The Series.mean() method

The syntax for this method is as follows:

DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

For this example, we will determine the average wins, losses, and ties for our Hockey Teams.

Code Example 1

df_teams = pd.DataFrame({'Bruins':    [4, 5,  9],
'Oilers':    [3, 6, 14],
'Leafs':     [2, 7, 11],
'Flames':    [21, 8, 7]})

result = df_teams.mean(axis=0).apply(lambda x:round(x,2))
print(result)
• Line [1] creates a DataFrame from a Dictionary of Lists and saves it to df_teams.
• Line [2] uses the mean() method with the axis parameter set to columns to calculate means (averages) from the DataFrame. The lambda function formats the output to two (2) decimal places. This output saves to the result variable.
• Line [3] outputs the result to the terminal.

Output

For this example, Alice Accord, an employee of Rivers Clothing, has logged her hours for the week. Let’s calculate the mean (average) hours worked per day.

Code Example 2

hours  = pd.Series([40.5, 37.5, 40, 55])
result = hours.mean()
print(result)
• Line [1] creates a Series of hours worked for the week and saves hours.
• Line [2] uses the mean() method to calculate the mean (average). This output saves to the result variable.
• Line [3] outputs the result to the terminal.

Output

42.25