Pandas Groupy只接受前N个群组 [英] Pandas Groupy take only the first N Groups

查看:72
本文介绍了Pandas Groupy只接受前N个群组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要按ID分组的DataFrame,例如g.:

I have some DataFrame which I want to group by the ID, e. g.:

import pandas as pd
df = pd.DataFrame({'item_id': ['a', 'a', 'b', 'b', 'b', 'c', 'd'], 'user_id': [1,2,1,1,3,1,5]})
print df

哪个生成:

  item_id  user_id
0       a        1
1       a        2
2       b        1
3       b        1
4       b        3
5       c        1
6       d        5

[7 rows x 2 columns]

我可以轻松按ID分组:

I can easily group by the id:

grouped = df.groupby("item_id")

但是如何仅返回前N个分组对象?例如我只需要前3个唯一的item_id.

But how can I return only the first N group-by objects? E. g. I want only the first 3 unique item_ids.

推荐答案

这是使用list(grouped)的一种方法.

result = [g[1] for g in list(grouped)[:3]]

# 1st
result[0]

  item_id  user_id
0       a        1
1       a        2

# 2nd
result[1]

  item_id  user_id
2       b        1
3       b        1
4       b        3

这篇关于Pandas Groupy只接受前N个群组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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