Python - Get the mean across multiple pandas dataframes

Learn, how can we find the mean across multiple pandas dataframe?
Submitted by Pranit Sharma, on August 12, 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 data.

What is mean?

The average of a particular set of values is the called mean of that set. Mathematically, it can be represented as:

Mean Formula

Mean across multiple pandas dataframes

Pandas allows us a direct method called mean() which calculates the average of the set passed into it.

To get the mean of multiple DataFrames, we need to concat the two DataFrames, and then we will use df[col].mean() method.

In pandas, we use pandas.DataFrame['col'].mean() directly to calculate the average value of a column. To concat two dataframes, we will use df.concat() method. Pandas concat() is used for combining or joining two DataFrames, but it is a method that appends or inserts one (or more) DataFrame below the other.

Let us understand with the help of an example,

Python program to get the mean across multiple pandas dataframes

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'Mahindra Sales':[19000,178922,18327,19337],
    'MG Sales':[9221,29711,128312,201831]
}

d2 = {
    'Hyundai Sales':[97849,74272,1973,193713],
    'Suzuki Sales':[974923,13719,18391,28841]
}

# Creating DataFrames
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

# Display Original DataFrames
print("Created DataFrame 1:\n",df1,"\n")
print("Created DataFrame: 2\n",df2,"\n")

# Finding mean of concatenated DataFrames
result = pd.concat([df1, df2, df2])

# Finding mean of concatenated DataFrame
result = result.mean()

# Display result
print("Result:\n",result)

Output

The output of the above program is:

Example: Get the mean across multiple pandas dataframes

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.