Instagram
youtube
Facebook
Twitter

Compute the Median Value of Each Group in a Pandas DataFrame

Compute the Median Value of Each Group in a Pandas DataFrame

Short Description of the Program:
This program groups the dataset by the 'Gender' column and calculates the median of numeric values (like age) for each group.

Explanation:

  • groupby('Gender'): Separates data based on gender.
     
  • .median(): Finds the middle (median) value in each numeric column of each group.
     
  • It's useful for understanding the central tendency without being skewed by outliers.
     

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_median = df.groupby('Gender').median(numeric_only=True)

print(group_median)