简体   繁体   English

使用原始数据框的熊猫条形图

[英]Pandas bar graph using original dataframe

I have a pandas dataframe and I'm attempting to plot the number of subscription types purchased by gender the original dataframe resemblems我有一个熊猫数据框,我正在尝试绘制按性别购买的订阅类型的数量,原始数据框类似于

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
...

At the moment I make a temp_df where I sum up the data so that I have目前我做了一个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()

This fills up temp_df and I'm able to graph it.这填满了temp_df并且我可以绘制它。 Is there an eloquent way of performing the same thing using just df ?是否有一种雄辩的方法可以仅使用df来执行相同的操作?

You can use groupby().sum() to replace the temp_df :您可以使用groupby().sum()替换temp_df

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM