Pandas: Get top 10 values AFTER grouping

流过昼夜 提交于 2019-12-23 02:36:53

问题


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

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?


回答1:


Is this what you're looking for?

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


来源:https://stackoverflow.com/questions/33168397/pandas-get-top-10-values-after-grouping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!