pandas Python:从数据透视表熊猫数据框创建条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50396479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Creating bar plot from pivot table pandas data frame
提问by LOR121
I'm new to python and was wondering how to create a barplot on this data I created using pivot table function.
我是 python 的新手,想知道如何在我使用数据透视表函数创建的数据上创建条形图。
#Create a pivot table for handicaps count calculation for no-show people based on their gender
pv = pd.pivot_table(df_main, values=['hipertension','diabetes','alcoholism'],
columns='status',index='gender',aggfunc=np.sum)
#Reshape the pivot table for easier calculation
data_pv = pv.unstack().unstack('status').reset_index().rename(columns={'level_0':'category','No-Show':'no_show', 'Show-Up':'show_up'})
data_pv['no_show_prop'] = (data_pv['no_show']/
(data_pv['no_show']+data_pv['show_up']))*100
data_pv
And as a result:
结果:
status category gender no_show show_up no_show_prop
0 alcoholism F 308 915 25.183974
1 alcoholism M 369 1768 17.267197
2 diabetes F 1017 4589 18.141277
3 diabetes M 413 1924 17.672229
4 hipertension F 2657 12682 17.321859
5 hipertension M 1115 5347 17.254720
I want to create a bar graph with category as x-axis and no_show_prop as y-axis with two different colors bars indicate female and male for each category. I also tried using groupby but it's not come out as I wanted to be.
我想创建一个条形图,类别为 x 轴,no_show_prop 为 y 轴,两个不同颜色的条形表示每个类别的女性和男性。我也尝试过使用 groupby 但它并没有像我想要的那样出现。
回答by thesilkworm
I think this should do what you're looking for. Starting with your current data_pv
, you can do the following to reshape the data into a form that's easier to plot in the way that you want.
我认为这应该可以满足您的要求。从您当前的 开始data_pv
,您可以执行以下操作,将数据重塑为更容易以您想要的方式进行绘图的形式。
df = data_pv.pivot(index='category', columns='gender', values='no_show_prop')
df
now looks like:
df
现在看起来像:
gender F M
category
alcoholism 25.183974 17.267197
diabetes 18.141277 17.672229
hipertension 17.321859 17.254720
Then you can simply do:
然后你可以简单地做:
df.plot(kind='bar')