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