如何将每个类别的前2项放入未堆叠的条形图



我需要创建一个未堆叠的barchart表,显示每个商品类别的前两名畅销书。

Example Input:
item_quant | item_name | item_category
1.0        | hellokitty| toy
2.0        | mighyapple| fruit
4.0        | winnypooh | toy
2.0        | tatatu.   | toy

对于item_category玩具,购买量最高的订单由item_name完成:winnypooh 4.0和tatatu 2.0。对于item_category水果,购买量最高的订单由item_names:mighyapple 2.0完成,没有第二个条目。

现在,我想创建一个未堆叠的条形图,在x轴上绘制item_category,在y轴上绘制item_quant。但是,需要按项目名称进行细分。不过,只有前2名的情节!

我该怎么做?

请尝试

df.groupby(['item_category','item_name'])['item_quant'].sum().nlargest(2).unstack().plot(kind ='bar', stacked=True)

计算总和时的groupbyitem_category和item_name

.nlargest(2)应该给你每组中的前2个

.plot(kind ='bar', stacked=True)指定要绘制堆叠的条形图

最新更新