gpt4 book ai didi

python - Pandas 多索引数据框获得每个排序组的前 5 行

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:03 25 4
gpt4 key购买 nike

我有一个如下所示的多索引 DataFrame:

enter image description here

我想对每个海报组进行排序(降序)并获得前 5 名。发帖人少于5人,取消记录。

最佳答案

假设您有以下 DF:

In [97]: df
Out[97]:
Time
waller poster
1 11 2
22 3
33 1
44 1
55 1
2 33 1
3 11 1
22 1
33 1
44 2
55 1
66 3

解决方案:

In [98]: (df.sort_index(ascending=[1,0])
...: .groupby(level=0, as_index=False)
...: .apply(lambda x: x.head(5) if len(x) >= 5 else x.head(0))
...: .reset_index(level=0, drop=True)
...: )
...:
Out[98]:
Time
waller poster
1 55 1
44 1
33 1
22 3
11 2
3 66 3
55 1
44 2
33 1
22 1

关于python - Pandas 多索引数据框获得每个排序组的前 5 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40449938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com