我的数据集如下所示:

ID   |    country
1    |    USA
2    |    USA
3    |    Zimbabwe
4    |    Germany


我执行以下操作以获取第一个国家的名称及其相应的值。所以在我的情况下是:

df.groupby(['country']).country.value_counts().nlargest(5).index[0]
df.groupby(['country']).country.value_counts().nlargest(5)[0]
df.groupby(['country']).country.value_counts().nlargest(5).index[1]
df.groupby(['country']).country.value_counts().nlargest(5)[1]
etc.


输出将是:

(USA), 388
(DEU), 245
etc.


然后重复一遍,直到获得数据集中的前5个国家/地区。

但是,如何获得“其他”或“其他”列,以便将所有其他国家/地区合并在一起。因此,以下国家/地区在我的数据集中并不常见:


  津巴布韦,伊拉克,马来西亚,肯尼亚,澳大利亚等


因此,我希望输出的第六个值如下所示:

(其他),3728

如何在熊猫中实现这一目标?

最佳答案

使用:

N = 5
#get counts of column
s = df.country.value_counts()
#select top 5 values
out = s.iloc[:N]
#add sum of another values
out.loc['Other'] = s.iloc[N:].sum()


最后如果需要2列DataFrame:

df = out.reset_index()
df.columns=['country','count']

关于python - 取最大5并以 Pandas 的总和/计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54327574/

10-12 19:38