Reputation: 125
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...
Upvotes: 0
Views: 441
Reputation: 15872
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
Upvotes: 2