Instagram
youtube
Facebook
Twitter

Compute the Size of Each Group in a Pandas DataFrame

Compute the Size of Each Group in a Pandas DataFrame

Short Description of the Program:
This program groups the DataFrame by the 'Gender' column and computes how many rows (entries) are in each group.

Explanation:

  • groupby('Gender') splits the data based on gender.
     
  • .size() counts the number of rows in each group.
     
  • The output shows the count of records for 'Male' and 'Female'.
     

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_size = df.groupby('Gender').size()

print(group_size)