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.