微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当大于组数时,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))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐