如何使用AGG获得第一位和第二个最大值?
我有一个数据框架:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
nlargest(n)
(在这里文档)Use
nlargest(n)
(here the docs)