在pandas中将行合并为“其他”

6

I have a pandas dataframe like this:

  character  count
0         a    104
1         b     30
2         c    210
3         d     40
4         e    189
5         f     20
6         g     10

我希望在数据框中仅保留前三个字符,其余字符则合并为others,因此表格变成:

  character  count
0         c    210
1         e    189
2         a    104
3    others    100

我该如何实现这个目标?

谢谢。

1个回答

7
我们可以使用Series.nlargest()方法来处理相关问题。该方法的具体用法可以参考官方文档
In [31]: new = df.nlargest(3, columns='count')

In [32]: new = pd.concat(
    ...:         [new,
    ...:          pd.DataFrame({'character':['others'],
    ...:                        'count':df.drop(new.index)['count'].sum()})
    ...:         ], ignore_index=True)
    ...:

In [33]: new
Out[33]:
  character  count
0         c    210
1         e    189
2         a    104
3    others     60

或者比较不太符合惯用语的解决方案:

In [16]: new = df.nlargest(3, columns='count')

In [17]: new.loc[len(new)] = ['others', df.drop(new.index)['count'].sum()]

In [18]: new
Out[18]:
  character  count
2         c    210
4         e    189
0         a    104
3    others    100

2
只需添加 new.reset_index(inplace=True, drop=True) 即可获得精确匹配 :) - zipa
@zipa,是的,谢谢!我要改进我的解决方案 - 我不喜欢它。 - MaxU - stand with Ukraine
@nt.jin,很高兴我能帮到你 :) - MaxU - stand with Ukraine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接