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)
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
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!