繁体   English   中英

当N大于组数时,最大(N)的行为?

[英]Behaviour of nlargest(N) when N greater than number of groups?

我已经从以下列表构建了一个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每组具有相同n_legs的前4个条目(按age排序)。

为此,我试过了

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM