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
96 views
in Technique[技术] by (71.8m points)

python - How do we change the result of groupby into dataframe?

df = pd.DataFrame({
    "A" : [1, 2, 1, 2, 1, 2, 2, 1],
    "B" : [1, 1, 2, 2, 1, 1, 1, 2],
    "C": [1, 1, 1, 1, 2, 2, 2, 2]})
df

This is my data.

and I used

gbA = df.groupby("A")

How can we change the result of this back to dataframe?

I read the other posts but I still do not get it...

question from:https://stackoverflow.com/questions/65907350/how-do-we-change-the-result-of-groupby-into-dataframe

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

1 Answer

0 votes
by (71.8m points)

If you want the original df back, use pandas.DataFrame.groupby.apply with a dummy function:

>>> gbA.apply(lambda x:x)
   A  B  C
0  1  1  1
1  2  1  1
2  1  2  1
3  2  2  1
4  1  1  2
5  2  1  2
6  2  1  2
7  1  2  2

If you want the groups, use dict comprehension:

>>> {k: v for k,v in gbA}
{1:    A  B  C
 0  1  1  1
 2  1  2  1
 4  1  1  2
 7  1  2  2,
 2:    A  B  C
 1  2  1  1
 3  2  2  1
 5  2  1  2
 6  2  1  2}

If you want the grouped df, where A set as index, use pandas.DataFrame.set_index 'A' with append=True to keep the original indices intact. Then pandas.DataFrame.swaplevel, to swap the multiindex levels, and finally pandas.DataFrame.sort_index along level=0 :

>>> df.set_index('A', append=True).swaplevel().sort_index(level=0)
     B  C
A        
1 0  1  1
  2  2  1
  4  1  2
  7  2  2
2 1  1  1
  3  2  1
  5  1  2
  6  1  2

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

...