如何使用AGG获得第一位和第二个最大值?

发布于 2025-02-08 11:38:01 字数 648 浏览 3 评论 0原文

我有一个数据框架:

id   type1           val
a    main             3
a    main             5
a    main             4
b    second           80
b    second           90

我想在Val的列ID type1和Max()上进行组,并获得最大观察的相应索引。我这样做:

df.groupby(["id","type1"])["val"].agg("max", "idxmax")

我得到了:

id   type1        max   idxmax   

a    main          5    1
b   second        90    4

但是我想获得第一位和第二个最大值:

id   type1        max   idxmax   

a    main          5    1
a    main          4    2
b   second        90    4
b    second       80    3

该怎么做?

I have a dataframe:

id   type1           val
a    main             3
a    main             5
a    main             4
b    second           80
b    second           90

I want to do groupby on columns id type1 and max() by val and also get the corresponding index of the max observation. I do this:

df.groupby(["id","type1"])["val"].agg("max", "idxmax")

I get:

id   type1        max   idxmax   

a    main          5    1
b   second        90    4

But i want to get first and second max:

id   type1        max   idxmax   

a    main          5    1
a    main          4    2
b   second        90    4
b    second       80    3

How to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南城旧梦 2025-02-15 11:38:01

使用nlargest(n)在这里文档)

df.groupby(["id","type1"])["val"].agg("nlargest", 2)

id  type1    
a   main    1     5
            2     4
b   second  4    90
            3    80

Use nlargest(n) (here the docs)

df.groupby(["id","type1"])["val"].agg("nlargest", 2)

id  type1    
a   main    1     5
            2     4
b   second  4    90
            3    80
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文