当大于组数时,nlargest(N)的行为?
作者:互联网
我已经从以下列表构建了一个DataFrame
df_list_1 = [{"animal": "dog", "color": "red", "age": 4, "n_legs": 4,},
{"animal": "dog", "color": "blue", "age": 4, "n_legs": 3},
{"animal": "cat", "color": "blue", "age": 4, "n_legs": 4},
{"animal": "dog", "color": "yellow", "age": 5, "n_legs":2},
{"animal": "dog", "color": "white", "age": 4, "n_legs": 2},
{"animal": "dog", "color": "black", "age": 4, "n_legs": 4},
{"animal": "cat", "color": "brown", "age": 4, "n_legs": 4}]
我现在想获得一个新的数据框,该数据框仅显示每个具有相同n_legs的组的前4个条目(按年龄排序).
为此,我尝试了
dfg = df_1.set_index(["animal", 'color']).groupby("n_legs")['age'].nlargest(4).reset_index()
但这给了我一个数据帧,其中删除了n_legs列.
animal color age
0 dog red 4
1 dog blue 4
2 cat blue 4
3 dog yellow 5
4 dog white 4
5 dog black 4
6 cat brown 4
我猜这是因为4等于最大组中的元素数.事实上,如果我这样做
dfg = df_1.set_index(["animal", 'color']).groupby("n_legs")['age'].nlargest(3).reset_index()
我得到以下
n_legs animal color age
0 2 dog yellow 5
1 2 dog white 4
2 3 dog blue 4
3 4 dog red 4
4 4 cat blue 4
5 4 dog black 4
这是预期的行为吗?
即使使用nlargest(N)且N大于最大组中元素的数量,有没有办法始终显示列?
谢谢!
解决方法:
我认为这是bug 16345.
替代解决方案效果很好,而且运行速度明显更快-首先sort_values
,然后致电GroupBy.head
:
dfg = (df_1.sort_values(["animal", 'color','age'], ascending=[False, False, True])
.groupby("n_legs")
.head(4))
标签:pandas-groupby,pandas,python 来源: https://codeday.me/bug/20191211/2106432.html