簡體   English   中英

如何使用 Pandas 聚合組指標並繪制數據

[英]How to aggregate group metrics and plot data with pandas

我想要一個餅圖來比較幸存者的年齡組。 問題是我不知道如何計算同齡人。 正如您在屏幕截圖底部看到的,它顯示 142 列。 但是,數據集中有 891 人。

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)

輸出

在此處輸入圖片說明

調用df_t.groupby(['Age', 'Survived']).size().reset_index(name='count')創建一個數據df_t.groupby(['Age', 'Survived']).size().reset_index(name='count') ,每個年齡和每個幸存狀態一行。

要獲得每個年齡組的計數,可以將“年齡組”列添加到原始數據框中。 在下一步中, groupby可以使用該“年齡組”。

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()

每個年齡組計數的餅圖

import pandas as pd
import seaborn as sns

# load data
df = sns.load_dataset('titanic')
df.columns = df.columns.str.title()

# map 0 and 1 of Survived to a string
df.Survived = df.Survived.map({0: 'Died', 1: 'Survived'})

# bin the age
df['Age Group'] = pd.cut(x=df['Age'], bins=[0, 18, 60, 100], labels=['Young', 'Middle Aged', 'Senior'])

# Calculate the counts
ct = pd.crosstab(df['Survived'], df['Age Group'])

# display(ct)
Age Group  Young  Middle Aged  Senior
Survived                             
Died          69          338      17
Survived      70          215       5

# plot
ax = ct.plot(kind='bar', rot=0, xlabel='')

# optionally add annotations
for c in ax.containers:
    ax.bar_label(c, label_type='edge')
    
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM