SlowlyLearning
SlowlyLearning

Reputation: 135

DataFrame 'groupby' is fixing group columns with index

I have used a simple 'groupby' to condense rows in a Pandas dataframe:

df = df.groupby(['col1', 'col2', 'col3']).sum()

In the new DataFrame 'df', the three columns that were used in the 'groupby' function are now fixed within the index and are no longer column indexes 0, 1 and 2 - what was previously column index 4 is now column index 0.

How do I stop this from happening / reinclude the three 'groupby' columns along with the original data?

Upvotes: 0

Views: 555

Answers (2)

Nk03
Nk03

Reputation: 14949

Try -

df = df.groupby(['col1', 'col2', 'col3'], as_index = False).sum()
#or
df = df.groupby(['col1', 'col2', 'col3']).sum().reset_index()

Upvotes: 1

imdevskp
imdevskp

Reputation: 2223

Try resetting the index

df = df.reset_index()

Upvotes: 1

Related Questions