Home > Backend Development > Python Tutorial > How to Explode List Columns in Pandas to Create Separate Rows?

How to Explode List Columns in Pandas to Create Separate Rows?

Patricia Arquette
Release: 2024-11-10 02:26:02
Original
982 people have browsed it

How to Explode List Columns in Pandas to Create Separate Rows?

Exploding List Columns in Pandas to Create Separate Rows

Exploding a list contained within a Pandas dataframe column allows for the creation of separate rows for each list value. This operation is particularly useful when dealing with data containing nested structures.

To achieve this explosion, Pandas 0.25 introduced the convenient explode() method. Consider the following example:

df = pd.DataFrame({
    'name': ['A.J. Price'] * 3,
    'opponent': ['76ers', 'blazers', 'bobcats'],
    'nearest_neighbors': [['Zach LaVine', 'Jeremy Lin', 'Nate Robinson', 'Isaia']] * 3
}).set_index(['name', 'opponent'])
Copy after login

This data contains a list of nearest neighbors for each player in the nearest_neighbors column. To create separate rows for each neighbor:

df_exploded = df.explode('nearest_neighbors')
Copy after login

Output:

                    nearest_neighbors
name       opponent                  
A.J. Price 76ers          Zach LaVine
           76ers           Jeremy Lin
           76ers        Nate Robinson
           76ers                Isaia
           blazers        Zach LaVine
           blazers         Jeremy Lin
           blazers      Nate Robinson
           blazers              Isaia
           bobcats        Zach LaVine
           bobcats         Jeremy Lin
           bobcats      Nate Robinson
           bobcats              Isaia
Copy after login

This technique simplifies the process of unfolding list columns, providing a clean and efficient way to work with nested data in Pandas.

The above is the detailed content of How to Explode List Columns in Pandas to Create Separate Rows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template