Categories
Python Answers

How to create a row for each list element from a Python Pandas column of lists?

Spread the love

Sometimes, we want to create a row for each list element from a Python Pandas column of lists.

In this article, we’ll look at how to create a row for each list element from a Python Pandas column of lists.

How to create a row for each list element from a Python Pandas column of lists?

To create a row for each list element from a Python Pandas column of lists, we call explode with the column with the lists to create the rows from.

For instance, we write

df = pd.DataFrame({
    'var1': [['a', 'b', 'c'], ['d', 'e',], [], np.nan], 
    'var2': [1, 2, 3, 4]
})
df.explode('var1')

to call explode with 'var' to unpack the lists in the var1 column and create column values from them.

We can reset the indexes by calling explode with `reset_index

df.explode('var1').reset_index(drop=True)

so that the indexes are updated after creating the next values.

Conclusion

To create a row for each list element from a Python Pandas column of lists, we call explode with the column with the lists to create the rows from.

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 *