How to Calculate Average of Selected Rows Based on Criteria of Dataframe in Python
To calculate the average of selected rows based on criteria of a dataframe in Python, you can use the mean() function.
Method: Use mean() Function
dataframe.loc[condition].mean()
The following example shows how to calculate the average of selected rows of a dataframe in Python.
Using mean() Function
We can use the mean() function to calculate the average of selected rows based on criteria.
Suppose we have the following dataframe:
# Import pandas library
import pandas as pd
# Create dataframe
office_stuff = pd.DataFrame({
'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
'Price': [4500, 550, 250, 50, 350, 50],
'Status': [1, 1, 1, 0, 1, 1]
})
# Filter rows based on the Status column and select only available products
available_products = office_stuff.loc[office_stuff['Status'] == 1]
# Calculate the average price of available products
average_price = available_products['Price'].mean()
# Print the average price
print('The average price of available products is:', average_price)
Output: 👇️
The average price of available products is: 1140.0
In this example, we filter the rows based on the Status column having a value of 1 and calculate the average price of the available products using the mean() function.