Home > Net >  Printing a groupby object in pandas
Printing a groupby object in pandas

Time:03-08

df.groupby("female").apply(display)

This displays all the groups in the dataset but my dataset is very large and my VScode crashed after I ran this since the output was long, So how to display only the first n groups, just to get an idea of how my grouped data looks like.

CodePudding user response:

You can use a generator. For example if you want to call only the first group, you can call next on generator once.

…
group_gen = (group for group in df.groupby("female"))

# get first group: returns tuple 
g = next(group_gen)

# show g
display(g[1])

Generators allows you to lazy load what you need.

To load N times you would call next N times

gs = pd.concat((next(group_gen)[1] for _ in range(N)), ignore_index=True)

display(gs)

CodePudding user response:

To follow up on the nice answer from @Prayson, you can use itertools.islice to get only the first few groups:

from itertools import islice

n = 5
top_n = list(islice(df.groupby('female'), n))
  • Related