简体   繁体   English

熊猫:groupby之后的样本组

[英]pandas: sample groups after groupby

How can I sample groups after a groupby in pandas? 在大熊猫分组之后如何采样分组? Say I want to get the first half of groups after groupby. 假设我要在groupby之后获得分组的前半部分。

In [194]: df = pd.DataFrame({'name':['john', 'george', 'john','andrew','Daniel','george','andrew','Daniel'], 'hits':[12,34,13,23,53,47,20,48]})
In [196]: grouped = df.groupby('name')

There are 'john', 'george', 'andrew', 'daniel' 4 groups in grouped and I'm interested in getting 2 groups out of the 4. It doesn't matter which 2 groups it returns. 有“ john”,“ george”,“ andrew”,“ daniel” 4个小组分组 ,我有兴趣从4个小组中分出2个小组。无论返回哪2个小组都没关系。

Thank you very much. 非常感谢你。

You can sample the names ahead of time and only group the chosen names: 您可以提前对名称进行采样,并且仅将所选名称分组:

selected_names = np.random.choice(df.name.unique(),2,replace = False)
grouped = df[df.name.isin(selected_names)].groupby('name')

Thanks for the quick replies, ajcr and cwharland. 感谢您的快速答复,ajcr和cwharland。 I was probably not clear about what I want, but your suggestions are great. 我可能不清楚我想要什么,但您的建议很好。 I did: 我做了:

choices =np.random.choice(grouped.indices.keys(), 2, replace=False)
df[df['name'].isin(choices)]

and get the results I hoped: 并得到我希望的结果:

Out[215]: 
   hits    name
0    12    john
2    13    john
3    23  andrew
6    20  andrew

Thank you both! 谢谢你俩!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM