Instagram
youtube
Facebook
Twitter

Compute the Mean Value of Each Group in a Pandas DataFrame

Compute the Mean Value of Each Group in a Pandas DataFrame

Short Description of the Program:
This program groups the DataFrame by the 'Gender' column and calculates the mean age within each group.

Explanation:

  • groupby('Gender'): Splits the data into Male and Female groups.
     
  • .mean(): Calculates the average of all numeric columns (in this case, only 'Age').
     
  • The result shows the average age for each gender.
     

Program:

import pandas as pd

data = {

    'Name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eva', 'Frank'],

    'Age': [25, 30, 22, 28, 26, 35],

    'Gender': ['Female', 'Male', 'Male', 'Female', 'Female', 'Male'],

    'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Seattle']
}
df = pd.DataFrame(data)

group_mean = df.groupby('Gender').mean(numeric_only=True)

print(group_mean)