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