ADVERTISEMENT
ADVERTISEMENT

How to create separate rows for each list item where the list is itself an item of a pandas DataFrame column?

Given a Pandas DataFrame where a column is having a list of items, we need to create separate row for each item of columns.
Submitted by Pranit Sharma, on June 01, 2022

We will use pandas.DataFrame.explode() method to achieve this task.

pandas.DataFrame.explode() Method

This is a special method which is used to convert each item of a column into a separate row, if the elements of a column consists of a list, then for each element of that list, pandas.DataFrame.explode() will create separate row.

Syntax:

DataFrame.explode(
    column, 
    ignore_index=False
    )

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'List':[['fish','bird','cat','dog'],[1,2,3]],
    'Col_2':[4,5]
}

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

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

Output:

Example 1: create separate rows for each list item

Now, use explode() method.

# Exploding the lists of column List
result = df.explode('List')

# Display result
print("Result:\n",result)

Output:

Example 2: create separate rows for each list item

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.