Instagram
youtube
Facebook
Twitter

Apply a Function to Each Group in a Pandas DataFrame

 Apply a Function to Each Group in a Pandas DataFrame

Short Description of the Program:
This program groups the DataFrame by 'Gender' and applies a custom function to return the row with the maximum age in each group.

Explanation:

  • groupby('Gender') splits the data by gender.
     
  • .apply(lambda x: ...) applies a lambda function to each group.
     
  • x['Age'].max() gives the highest age within each group.
     
  • The function returns rows that match the max age.
     

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)

max_age_group = df.groupby('Gender').apply(lambda x: x[x['Age'] == x['Age'].max()])

print(max_age_group)