我有一个熊猫数据框,我试图按性别购买原始数据框相似的订购类型的数量

df =
Memb_ID   Gender   1_Month   3_Month   6_Month   1_Year
1         Male     6         0         3         0
2         Male     0         0         0         4
3         Female   0         4         3         1
4         Male     2         1         0         1
5         Female   1         4         0         2
...


此刻,我创建一个temp_df,对数据求和,以便

temp_df = pd.DataFrame(columns=['Gender', '1_Year', '1_Month', '3_Month','6_Month'])

sex = ['Male', 'Female']
temp_df['Gender'] = sex

for i in list(temp_df.columns.values)[1:]:
    temp = [df.loc[df['Gender'] == 'Male', i].sum(),\
            df.loc[df['Gender'] == 'Female', i].sum()]
    temp_df[i] = temp

temp_df.plot(x='Gender', kind='bar', grid=True)
plt.show()


这填满了temp_df,我可以用图形表示。是否有一种雄辩的方法仅使用df执行相同的操作?

最佳答案

您可以使用groupby().sum()替换temp_df

ax = df.groupby('Gender')['1_Year','1_Month','3_Month','6_Month'].sum().plot.bar(grid=True)


python - 使用原始数据框的 Pandas 条形图-LMLPHP

关于python - 使用原始数据框的 Pandas 条形图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39925873/

10-12 16:37
查看更多