Skip to main content
 首页 » 编程设计

python之Pandas Python之对其他人进行分组计数

2024年11月24日12Free-Thinker

我正在为一个使用 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['国家'].value_counts().plot.pie()

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

我该怎么做?

请您参考如下方法:

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