假设我有 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 重命名为“其他”。完成后,我假设使用 groupby
和 sum
来完成剩下的工作。
预期输出为:
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/