条形图分组Pandas

2024-05-14 00:05:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于绘制分组数据帧数据的问题。你知道吗

数据如下所示:

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

到目前为止,我已经尝试将GroupByagg与以下内容结合使用:

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中,它看起来像:

enter image description here


Tags: 数据dfdatafood类别食物badgood