python - sum values in dictionary less than a certain value
问题描述
I have the following dictionary and am trying to make a pie chart from them but I want to only include the top 5 (they are already sorted by value here) and then sum the others together in an Other
category i.e. replace Publishing
, Fashion
, Food
etc. with just one Other
which sum them all together. Stuck with how to do this so would appreciate any help!
{'Games': 715067930.8599964,
'Design': 705237125.089998,
'Technology': 648570433.7599969,
'Film & Video': 379559714.56000066,
'Music': 191227757.8699999,
'Publishing': 130763828.65999977,
'Fashion': 125678824.47999984,
'Food': 122781563.58000016,
'Art': 89078801.8599998,
'Comics': 70600202.99999984,
'Theater': 42662109.69999992,
'Photography': 37709926.38000007,
'Crafts': 13953818.35000002,
'Dance': 12908120.519999994,
'Journalism': 12197353.370000007}
At the moment my pie chart is really overcrowded using this code
groupbycategorypledge = df.groupby('main_category')['usd_pledged_real'].sum().sort_values(ascending=False)
plt.figure(figsize=(20, 10))
pie = groupbycategorypledge.plot(kind='pie', startangle=90, radius=0.7, title='Amount Pledged by Main category',autopct='%1.1f%%',labeldistance=1.2)
plt.legend(loc=(1.05,0.75))
plt.ylabel('')
so I have
dict = groupbycategorypledge.sort_values(ascending=False).to_dict()
解决方案
您可以在使用 Pandas之前操作您的字典:
from operator import itemgetter
# sort by value descending
items_sorted = sorted(d.items(), key=itemgetter(1), reverse=True)
# calculate sum of others
others = ('Other', sum(map(itemgetter(1), items_sorted[5:])))
# construct dictionary
d = dict([*items_sorted[:5], others])
print(d)
{'Games': 715067930.8599964,
'Design': 705237125.089998,
'Technology': 648570433.7599969,
'Film & Video': 379559714.56000066,
'Music': 191227757.8699999,
'Other': 658334549.8999995}
推荐阅读
- struts - 如何更改 Struts 1.3 HTML 单选按钮的颜色
- python - 在 NetworkX 中创建大图时出现内存错误
- javascript - 在javascript中按布尔值、姓氏和名称对数组进行排序
- python-3.x - 状态更改为活动后,Tkinter 按钮未更改回正确的颜色
- r - 如何使用 dplyr 和 shift 添加新列并计算递归 cum
- node.js - 带有时间戳的 Winson 不添加时间戳
- c++ - 当我尝试运行我的 c++ 程序时,它说“使用未声明的标识符”,但它在标题中声明
- python - “ValueError : list.remove(x): x not in list”当 x 在列表中时
- repository - 安装 RCU for Oracle Data Integrator 运行时出错
- ios - Swift - 在 UIStackView 中以编程方式创建 UIPickerView