How to Unpack Nested Lists in DataFrames with Pandas?

Barbara Streisand
Release: 2024-11-13 07:28:02
Original
252 people have browsed it

How to Unpack Nested Lists in DataFrames with Pandas?

Exploding Nested Lists in DataFrames with Pandas

Challenge: Convert a DataFrame cell containing a list into separate rows for each value.

Consider a DataFrame with a column of opponent names and a corresponding column of nearest neighbors, represented as a list. The goal is to unpack these lists, stacking each neighbor as a separate row for its corresponding opponent.

Solution:

Pandas has simplified this operation with the explode() method in version 0.25:

import pandas as pd

# Sample DataFrame
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']))

# Explode the 'nearest_neighbors' column
df = df.explode('nearest_neighbors')

# Print the exploded DataFrame
print(df)
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

The above is the detailed content of How to Unpack Nested Lists in DataFrames with Pandas?. 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