python - 字典中的总和值小于某个值

标签 python sorting dictionary aggregate

我有以下字典,正在尝试根据它们制作一个饼图,但我只想包括前 5 个(它们已经在此处按值排序),然后将其他的汇总到 Other 类别,即将 PublishingFashionFood 等替换为一个 Other,将它们加在一起。坚持如何做到这一点,所以将不胜感激任何帮助!

{'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}

目前使用这段代码我的饼图真的很拥挤

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('')

所以我有

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}

关于python - 字典中的总和值小于某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682620/

相关文章:

python - 如何成功地将 python-telegram-bot 安装到 Termux 中?

c++ - 包含按值对映射进行排序的键的 vector

c# - 按字母顺序对字符串中的数字进行排序

python - 当它的键未知时从字典中删除一个项目

python - 按python中的第一个元素重新组合子列表

python - 无法安装ABP爬虫

python - json.load 在加载带有拉丁字符的文件时出错

python - 传递一个变量以从 Python 中的 JSON 字符串中提取?

c++ - 如何将文件读入数组,然后对数据进行排序?

python - 如何递归字典并动态更新值以便以后可以引用它们?