0

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?

2 Answers 2

1

Try -

df = df.groupby(['col1', 'col2', 'col3'], as_index = False).sum()
#or
df = df.groupby(['col1', 'col2', 'col3']).sum().reset_index()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - this was really stupid of me. I thought reset_index was only for resetting row indexes, for example after I had dropped rows.
1

Try resetting the index

df = df.reset_index()

1 Comment

Thanks - this was really stupid of me. I thought reset_index was only for resetting row indexes, for example after I had dropped rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.