Pandas:分组后获取前 10 个值 [英] Pandas: Get top 10 values AFTER grouping

查看:512
本文介绍了Pandas:分组后获取前 10 个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有id"列和value"列的 Pandas 数据框.它已经按第一个 id(升序)然后是值(降序)排序.我需要的是每个 id 的前 10 个值.

I have a pandas data frame with a column 'id' and a column 'value'. It is already sorted by first id (ascending) and then value (descending). What I need is the top 10 values per id.

我认为类似以下内容会起作用,但它不会:

I assumed that something like the following would work, but it doesn't:

df.groupby("id", as_index=False).aggregate(lambda (index,rows) : rows.iloc[:10])

我得到的只是一个 id 列表,值列(以及我在问题中省略的其他列)不再存在.

What I get is just a list of ids, the value column (and other columns that I omitted for the question) aren't there anymore.

有什么想法可以在不遍历每一行并将前十行附加到另一个数据结构的情况下完成的吗?

Any ideas how it might be done, without iterating through each of the single rows and appending the first ten to another data structure?

推荐答案

这是您要找的吗?

df.groupby('id').head(10)

这篇关于Pandas:分组后获取前 10 个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆