python - 在饼图中显示三个最佳项目并将其余项目总结为其他
问题描述
我想在圆图中显示购买中出现的商品数量。仅将前 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))
我目前拥有的
我想要什么(注意,这些数据只是愚蠢的。它们与上面的数据没有任何共同之处。这些数据应该只代表我想要的)
解决方案
在这个答案中,我假设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()
推荐阅读
- fluent-migrator - 从在多个服务器上运行的应用程序运行进程内迁移是否安全?
- php - 升级后端服务器后,PHP 未通过 POST/CURL 发送任何参数(前端服务器没有变化)
- python - 路径名中的编码字符
- java - 没有可用的名为 xxx 的 bean
- mysql - MySQL 5.7 准备好的语句更新了错误的时间戳列
- javascript - 如何修复“未捕获的类型错误:无法读取未定义的属性‘编号’”?
- websphere - 有没有办法列出来自不同主机的 Websphere 的所有服务器状态?
- jquery - 我想禁用 dayclick 事件
- sql - 通过 2 个参数查找记录,其中一个是数组
- php - 无法连接到 Lightsail 托管数据库 - (HY000/2002):连接被拒绝