Categories
Python Answers

How to explode a list inside a Dataframe cell into separate rows with Python Pandas?

Spread the love

To explode a list inside a Dataframe cell into separate rows with Python Pandas, we call the met method.

For instance, we write

pd.melt(df.nearest_neighbors.apply(pd.Series).reset_index(), 
             id_vars=['name', 'opponent'],
             value_name='nearest_neighbors')
     .set_index(['name', 'opponent'])
     .drop('variable', axis=1)
     .dropna()
     .sort_index()

to call melt with the nearest_neighbors column.

We call nearest_neighbors.apply to get the name and opponent column values.

And then we call drop to drop the variable column.

dropna removes the NaN values.

And sort_index sorts the values by the index values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *