Python 带分类列计数的分组条形图
我有一个dataframe,它有很多列,其中两列是y和Poutcom。它们都是分类数据。我使用子条形图poutcome基于y生成一个分组条形图。我试着创建一个小组,结果如下Python 带分类列计数的分组条形图,python,Python,我有一个dataframe,它有很多列,其中两列是y和Poutcom。它们都是分类数据。我使用子条形图poutcome基于y生成一个分组条形图。我试着创建一个小组,结果如下 y poutcome no failure 427 other 159 success 46 unknown 3368 yes failure 63 other 38 success
y poutcome
no failure 427
other 159
success 46
unknown 3368
yes failure 63
other 38
success 83
unknown 337
基于按dataframe分组的结果,我认为它将生成一个如下图,图例和彩色条将是failure、success、other和unknown,它们将按yes和no进行分组(在示例图中,4和5将是yes和no)。你明白要点了
分组依据是thisbank.groupby(['y','poutcomme'])['poutcomme'].count()
,但与上面的显示类似,我的显示如下
我如何使它像第一个图形?这些条表示poutcome,它们按y分组,您应该能够在打印之前:
grouped.unstack(级别=1.plot.bar)()
这是我最初使用的数据帧:
y poutcome count
0 no failure 427
1 no other 159
2 no success 46
3 no unknown 3368
4 yes failure 63
5 yes other 38
6 yes success 83
7 yes unknown 337
您应该能够通过将as_index=False设置为
然后,可以使用来排列用于打印的值:
df.pivot(index=“poutcom”,columns=“y”,values=“count”)
#不,是的
#鸡汤
#故障42763
#其他159 38
#成功46 83
#未知3368337
#并绘制出:
df.pivot(index=“poutcom”,columns=“y”,values=“count”).plot.bar()
或者在图例中使用poutcom
交换索引和列参数:
df.pivot(index=“y”、columns=“poutcom”、values=“count”).plot.bar()