Python - How to convert column with list of values into rows in pandas dataframe?

Given a Pandas DataFrame, we have to convert its column with list of values into rows.
Submitted by Pranit Sharma, on September 05, 2022

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 in which one column contains the list of values as a value, we need to extract all the values of the list and add each of these values into a separate new row.

Converting column with list of values into rows

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

Let us understand with the help of an example,

Python program to convert column with list of values into rows in pandas dataframe

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'Name':['Ram','Shyam','Seeta','Geeta'],
    'Age':[[20,30,40],23,36,29]
}

# Creating DataFrame
df = pd.DataFrame(d1)

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

# Exploding the column age 
# where we encounter the list
df = df.explode('Age')

# Display modified DataFrame
print("Modified DataFrame:\n",df,"\n")

Output

The output of the above program is:

Example: Convert column with list of values into rows

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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