python - 对 pandas df 中的前 N ​​组和组 'others' 进行排序

标签 python pandas

假设我有 df

import pandas as pd

dic = {'001': [14],
       '002': [3],
       '003': [2],
       '004': [6],
       '005': [7],
       '006': [1],
       '007': [2]}
df = pd.DataFrame.from_dict(dic,orient='index')
df.reset_index(inplace=True)
df = df.rename(columns = {'index':'id',0:'count'})
sorted = df.sort_values('count',ascending=False)
print(sorted)

结果

    id  count
0  001     14
4  005      7
3  004      6
1  002      3
2  003      2
6  007      2
5  006      1

我想按计数列对前 3 个进行排序,并将其余的分组为“其他”。我想我想做一些类似 not_top3 =排序[3:] 的事情,但无法弄清楚如何将 id 重命名为“其他”。完成后,我假设使用 groupbysum 来完成剩下的工作。

预期输出为:

    id  count
0  001     14
1  005      7
2  004      6
3  other    8

其中“other”是剩余 id 的总和。

最佳答案

您可以使用df.append在底部添加一行。

sorted_df = df.sort_values("count", ascending=False)
out = sorted_df.iloc[:3]
out.append(
    {"id": "others", "count": sorted_df["count"].iloc[3:].sum()},
    ignore_index=True,
)

       id  count
0     001     14
1     005      7
2     004      6
3  others      8

关于python - 对 pandas df 中的前 N ​​组和组 'others' 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67142016/

相关文章:

python - Python-打印回溯

Python 3 : Tkinter: How to change Entry. get() 成整数

python - 将自定义 numba njit 函数应用于 pandas 滚动对象

python - 如何对 pandas 数据框应用两个样本比例测试?

python - 如何使用 bool 开关更新 Dash 中的图形?

python - tkinter 协议(protocol) WM_DELETE_WINDOW 不适用于额外的窗口

python - pandas df.apply TypeError 数据类型不理解

python - 如何使用 for 循环将首次使用日期存储在字典中

python - 如何在 github 工作流程的下一步中设置和访问 python 代码的响应

python - 对象 pandas 没有属性名称 Series