首页 > 解决方案 > Pandas Python - 对其他人进行分组计数

问题描述

我正在使用 python 和 pandas 对一个项目进行数据分析,其中我有以下数据:

数字是计数。

USA: 5000
Canada: 7000
UK: 6000
France: 6500
Spain: 4000
Japan: 5
China: 7
Hong Kong: 10
Taiwan: 6
New Zealand: 8
South Africa: 11

我的任务是制作一个代表计数的饼图。

df['Country'].value_counts().plot.pie()

我将得到一个饼图,但我想将计数较小的国家/地区组合起来,并将它们归入与其他类似的类别。

我怎样才能做到这一点?

标签: pythonpandas

解决方案


IIUC 使用np.where设置边界,然后groupby+ sum,注意我在这里使用pandas.Series.groupby

s=df['Country'].value_counts()
s.groupby(np.where(s>=4000,s.index,'other')).sum()#.plot.pie()
Out[64]: 
Canada    7000
France    6500
Spain     4000
UK        6000
USA       5000
other       47

推荐阅读