我有一个关于绘制分组数据帧数据的问题。你知道吗
数据如下所示:
data =
index taste food
0 good cheese
1 bad tomato
2 worse tomato
3 worse cheese
4 good meat
5 good meat
6 bad cheese
7 worse tomato
8 worse tomato
9 good cheese
10 worse meat
11 good meat
我想做的是有一个条形图,以每个口味类别为x轴(好的,坏的,坏的),以每个口味类别中每种食物类型的百分比分布为条形图。你知道吗
例如,看看味觉类别worse
,我们有:3 tomato
,1 cheese
和1 meat
。总共有3+1+1=5种食物类型,因此:
3/5=60%tomato
,
1/5=20%cheese
和
1/5=20%meat
到目前为止,我已经尝试将GroupBy
和agg
与以下内容结合使用:
df_1 = data.groupby(['taste', 'food']).agg({'taste' : 'count'})
df_2 = df_1.groupby(level=0).apply(lambda x: 100 * x / float(x.sum()))
这似乎产生了我想要的结果:
taste
taste food
bad cheese 50.0
tomato 50.0
good cheese 40.0
meat 60.0
worse cheese 20.0
meat 20.0
tomato 60.0
但现在我被困在如何实际策划这个!你知道吗
在Excel中,它看起来像:
我似乎找到了一个例子:
making a stacked barchart in pandas
充分的行动:
相关问题 更多 >
编程相关推荐