Menu Close

How to split cell into multiple rows in a Python Pandas dataframe?

Sometimes, we want to split cell into multiple rows in a Python Pandas dataframe.

In this article, we’ll look at how to split cell into multiple rows in a Python Pandas dataframe.

How to split cell into multiple rows in a Python Pandas dataframe?

To split cell into multiple rows in a Python Pandas dataframe, we can use the apply method.

For instance, we write

df.set_index(['order_id', 'order_date'])
   .apply(lambda x: x.str.split(',').explode())
   .reset_index()

to call apply with a lambda function that calls str.split to split the x string value.

And then we call explode to fill new rows with the split values.

Finally, we call `reset_index to reset the index numbers after filling the rows with the split values.

Conclusion

To split cell into multiple rows in a Python Pandas dataframe, we can use the apply method.

Posted in Python, Python Answers