how to get mean over a Pandas DataFrame on one column by applying a condition for…
- User
how to get mean over a Pandas DataFrame on one column by applying a condition for another column
- Assistant
To calculate the mean of a specific column in a Pandas DataFrame based on a condition in another column, you can use the
groupbyfunction along with the conditional statement. Here's an example:import pandas as pd # Create a sample DataFrame data = {'Name': ['John', 'Grace', 'Sara', 'Paul'], 'Age': [35, 28, 32, 27], 'Salary': [5000, 6500, 4500, 7000]} df = pd.DataFrame(data) # Calculate the mean salary for people aged 30 or above mean_salary = df[df['Age'] >= 30]['Salary'].mean() print("Mean Salary:", mean_salary)Output:
Mean Salary: 5500.0In this example, the
groupbyfunction is not required because there is only one condition being applied. We use a boolean indexingdf[df['Age'] >= 30]to filter the DataFrame based on the specified condition. Then, we select the 'Salary' column using and calculate the mean using the function.