挑战:将包含列表的 DataFrame 单元格转换为每个值的单独行。
考虑一个 DataFrame,其中包含一列对手名称和相应的最近邻居列,以列表形式表示。目标是解压这些列表,将每个邻居堆叠为对应对手的单独行。
解决方案:
Pandas 使用explode() 简化了此操作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)
输出:
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
以上是如何使用 Pandas 解压 DataFrame 中的嵌套列表?的详细内容。更多信息请关注PHP中文网其他相关文章!