Iterate over a subset of a Pandas groupby object

ぐ巨炮叔叔 提交于 2019-12-24 18:41:59

问题


I have a Pandas groupby object, and I would like to iterate over the first n groups. I've tried:

import pandas as pd
df = pd.DataFrame({'A':['a','a','a','b','b','c','c','c','c','d','d'],
                   'B':[1,2,3,4,5,6,7,8,9,10,11]})

df_grouped = df.groupby('A')
i = 0
n = 2 # for instance
for name, group in df_grouped:
    #DO SOMETHING
    if i == n: 
        break
    i += 1 

and

group_list = list(df_grouped.groups.keys())[:n]
for name in group_list:
    group = df_grouped.get_group(name)
    #DO SOMETHING

but I wondered if there was a more elegant/pythonic way to do it?

My actual groupby has 1000s of groups within it, and I'd like to only perform an operation on a subset, just to get an impression of the data as a whole.


回答1:


You can filter with your original df, then we can do all the other you need to do

yourdf=df[df.groupby('A').ngroup()<=1]

yourdf=df[pd.factorize(df.A)[0]<=1]


来源:https://stackoverflow.com/questions/55971179/iterate-over-a-subset-of-a-pandas-groupby-object

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