Skip to content
Advertisement

How do I convert pandas.core.series.Series back to a Dataframe following a groupby?

I tried manipulating a Dataframe and the output was (unexpectedly) of a pandas.core.series.Series type while I was aiming for another Dataframe output.

For reference, the original Dataframe looked like this –

JavaScript

I was hoping to combine all consecutive rows with the same Character value. So, all ‘Leslie Knope’ lines from “Hello” to “I’m gonna put a lot of fun” would be rolled into one row, the “Child” line would stay as is and then the next two “Leslie Knope” lines would be rolled into one.

This is the code I used to achieve that (to an extent):

JavaScript

This is the df2 output –

JavaScript

I was hoping to get df2 as another Dataframe that collapses the consecutive lines spoken by the character as I wanted and have the lines in a Lines column. Not really sure what’s happening here since df2 is of pandas.core.series.Series type, so I would appreciate help with either of the following –

  1. An alternative approach to collapsing the consecutive lines spoken by the character
  2. A way to convert df2 to a Dataframe with the Key, Character, and Lines column.

Thanks in advance!

Advertisement

Answer

All you need to do is chain .reset_index() to your last line.

It became a series when you applied your groupby function to a single column (Lines). The other columns then became the index for your series.

Edit: to get rid of the ‘key’ column, just add `.drop(‘key’,axis=1)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement