Home > database >  How to aggregate group metrics and plot data with pandas
How to aggregate group metrics and plot data with pandas

Time:11-09

I want to have a pie chart that compares survived people's age groups. The problem is I don't know how to count people with the same age. As you see in the bottom of screenshot, it says 142 columns. But, there are 891 people in the dataset.

import pandas as pd
import seaborn as sns  # for test data only

# load test data from seaborn
df_t = sns.load_dataset('titanic')

# capitalize the column headers to match code used below
df_t.columns = df_t.columns.str.title()

dft = df_t.groupby(['Age', 'Survived']).size().reset_index(name='count')

def get_num_people_by_age_category(dft):
    dft["age_group"] = pd.cut(x=dft['Age'], bins=[0,18,60,100], labels=["young","middle_aged","old"])
    return dft

# Call function
dft = get_num_people_by_age_category(dft)
print(dft)

output

enter image description here

CodePudding user response:

Calling df_t.groupby(['Age', 'Survived']).size().reset_index(name='count') creates a dataframe with one line per age and per survived status.

To get the counts per age group, an "age group" column can be added to the original dataframe. And in a next step, groupby can use that "age group".

from matplotlib import pyplot as plt
import seaborn as sns  # to load the titanic dataset
import pandas as pd

df_t = sns.load_dataset('titanic')
df_t["age_group"] = pd.cut(x=df_t['age'], bins=[0, 18, 60, 100], labels=["young", "middle aged", "old"])

df_per_age = df_t.groupby(['age_group', 'survived']).size().reset_index(name='count')
labels = [f'{age_group},\n {"survived" if survived == 1 else "not survived"}'
          for age_group, survived in df_per_age[['age_group', 'survived']].values]
labels[-1] = labels[-1].replace('\n', ' ') # remove newline for the last items as the wedges are too thin
labels[-2] = labels[-2].replace('\n', ' ')
plt.pie(df_per_age['count'], labels=labels)
plt.tight_layout()
plt.show()

pie plot with counts per age group

CodePudding user response:

  • The enter image description here

  • Related