首页 > 解决方案 > 在饼图中显示三个最佳项目并将其余项目总结为其他

问题描述

我想在圆图中显示购买中出现的商品数量。仅将前 3 名产品作为一个整体列出,其余产品应汇总在Other.

   import pandas as pd
d = {'buyerid': [0,0,1,2,3,3,3,4,4,4],
         'itemid': [0,1,1,1,1,0,1,4,5,0],
         'description': ['Banana', 'Apple', 'Apple', 'Strawberry', 'Apple', 'Banana', 'Apple', 'Dog-Food', 'Beef', 'Banana',], }
df = pd.DataFrame(data=d)
display(df.head(10))
    
purch = df['buyerid'].nunique()
df1 = df.groupby(['itemid','description']).size().div(purch).reset_index(name='percentage')
print (df1)
    
   itemid description  percentage
0       0      Banana         0.6
1       1       Apple         0.8
2       1  Strawberry         0.2
3       4    Dog-Food         0.2
4       5        Beef         0.2

df_top = df[['itemid', 'percentage']].head(5)
plot = df_top .plot.pie(y='percentage', figsize=(7, 7))

我目前拥有的

在此处输入图像描述

我想要什么(注意,这些数据只是愚蠢的。它们与上面的数据没有任何共同之处。这些数据应该只代表我想要的)

在此处输入图像描述

标签: pythonmatplotlibcharts

解决方案


在这个答案中,我假设buyerid 和itemid 没有任何目的,请看看它是否是你想要的。

d = {'itemid': [0,1,1,1,1,0,1,4,5,0],
'description': ['Banana', 'Apple', 'Apple', 'Strawberry', 'Apple', 'Banana', 'Apple', 'Dog-Food', 'Beef', 'Banana',], }
df = pd.DataFrame(data=d)
ser = df.groupby('description')['itemid'].count()
### Combine categories
ser = ser.sort_values(ascending=False)
ser['Others'] = ser[3:].sum()
ser = ser.iloc[[0,1,2,-1]]
print(ser)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.pie(ser.values, labels=ser.index, startangle=90, autopct=lambda x:int(x/100.*ser.sum()), pctdistance=0.8, counterclock=False)
ax.legend()
plt.axis('equal')
plt.show()

在此处输入图像描述


推荐阅读