Split cell into multiple rows in pandas dataframe

Given a pandas dataframe, we have to split cell into multiple rows in it. By Pranit Sharma Last updated : October 02, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose, we have a DataFrame with multiple columns and a column containing multiple values and we want to split all these values and add them in a new row.

Splitting cell into multiple rows

For this purpose, we will use DataFrame.explode() method. It will allow us to convert all the values of a column into rows in pandas DataFrame.


The method is used to convert each element of a list-like to a row, replicating index values.



We will first set the index which we do not want to change and will use the apply method to use explode method.

Let us understand with the help of an example,

Python program to split cell into multiple rows in pandas dataframe

# Importing pandas package
import pandas as pd

# Importing display attribute from Ipython
from IPython.display import display

# Creating a dictionary
d = {

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# splitting cities column
res = df.set_index(['Product_id', 'Product_code']).apply(lambda x: x.str.split(',').explode()).reset_index()

# Display result


The output of the above program is:

Example: Split cell into multiple rows

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.