Convert GroupBy Object Back to pandas DataFrame in Python (Example) | type & reset_index Functions

preview_player
Показать описание
Python code of this video:

import pandas as pd # Import pandas library in Python

data = pd.DataFrame({'x1':[3, 5, 1, 2, 5, 7, 2, 8], # Create pandas DataFrame
'x2':range(1, 9),
'group1':['A', 'B', 'A', 'C', 'A', 'C', 'B', 'A'],
'group2':['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b']})
print(data) # Print pandas DataFrame

print(data_group) # Print aggregated data
# x1 x2
# group1 group2
# A a 2.0 2.0
# b 6.5 6.5
# B a 5.0 2.0
# b 2.0 7.0
# C a 2.0 4.0
# b 7.0 6.0

print(type(data_group)) # Check class of grouped data

print(data_group_new) # Print updated grouped data
# group1 group2 x1 x2
# 0 A a 2.0 2.0
# 1 A b 6.5 6.5
# 2 B a 5.0 2.0
# 3 B b 2.0 7.0
# 4 C a 2.0 4.0
# 5 C b 7.0 6.0

print(type(data_group_new)) # Check class of updated grouped data

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

Thank you, Joachim! I'm studying Python and this was a huge doubt that I had. I couldn't find it anywhere else. You helped me a lot, my friend! :)

apenasigao
Автор

This just saved me a lot of time and work. Thank you!!!

kelechiigwe
Автор

I've searched for this everywhere. In vain. Legendary. Thank you, sir !

torpedoe
Автор

Thanks for the helpful video. I believe you can also use the as_frame = False parameter in the groupby or .to_frame() method on the resulting groupby to convert it to a standard dataframe.

JazzKeys-mh