Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

python - Convert a pandas groupby object to list of dataframes

Say I have the following dataframe, and want to group-by the ys:

   xs  ys
0   0   0
1   1   0
2   2   1
3   3   1

I can do this by running

grouped = df.groupby('ys')

I can iterate through this new groupby object fine, but instead I want a list of the dataframes that are accessed by group in the following loop:

for name, group in grouped:
    do_something(group)

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sure, just iterate over the groups!

>>> import pandas as pd, numpy as np
>>> df = pd.DataFrame(dict(xs=list(range(4)), ys=[0,0,1,1]))
>>> df
   xs  ys
0   0   0
1   1   0
2   2   1
3   3   1
>>> grouped = df.groupby('ys')
>>> dataframes = [group for _, group in grouped]
>>> dataframes
[   xs  ys
0   0   0
1   1   0,    xs  ys
2   2   1
3   3   1]
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...