Home > Backend Development > Python Tutorial > How can I unpack lists in pandas DataFrames into individual rows?

How can I unpack lists in pandas DataFrames into individual rows?

Susan Sarandon
Release: 2024-11-13 09:24:02
Original
201 people have browsed it

How can I unpack lists in pandas DataFrames into individual rows?

Unpacking Lists in DataFrames into Individual Rows

In data manipulation scenarios, you may encounter the challenge of transforming a pandas cell containing a list into individual rows. To achieve this, you can leverage the functionality of pandas' explode() method.

Prior to pandas 0.25, handling this operation required more cumbersome approaches. However, the introduction of explode() has streamlined the process.

Consider the following example:

import pandas as pd

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

With the DataFrame above, you aim to unpack and stack the values in the nearest_neighbors column, resulting in each value becoming a row within each corresponding opponent.

Here's how you can accomplish this using the explode() method:

df.explode('nearest_neighbors')
Copy after login

The output will appear as follows:

                    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

By utilizing the explode() method, you effectively transform the original list-like column into rows, providing a more structured and manageable representation of your data.

The above is the detailed content of How can I unpack lists in pandas DataFrames into individual 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