Python Pandas-如何获取前n个值以及所有其他值的总和 [英] Python Pandas - how to get top n values and the sum of all other values

查看:904
本文介绍了Python Pandas-如何获取前n个值以及所有其他值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的Pandas DataFrame:

I have a Pandas DataFrame like this:

Browsers        Sessions
Chrome          201
IE              136
Safari          101
Firefox         36
SamsungBrowse   12
Opera           6  

我需要显示的是前3个值,并将其余值总和为其他":

and what I need is display top 3 values and sum the rest as 'other':

Browsers        Sessions
Chrome          201
IE              136
Safari          101
Other           54  

有什么想法可以做到这一点吗?

Any ideas how this could be done?

推荐答案

尝试一下:

In [39]: result = df.nlargest(3, columns='Sessions')

In [40]: result.loc[len(result)] = ['Others', df.loc[~df.Browsers.isin(result.Browsers), 'Sessions'].sum()]

In [41]: result
Out[41]:
  Browsers  Sessions
0   Chrome       201
1       IE       136
2   Safari       101
3   Others        54

这篇关于Python Pandas-如何获取前n个值以及所有其他值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆