pandas如何按行对应取子列表后展开DataFrame指定列
解决方法
思路很清晰,分两步操作即可:
- 第一步按行索引提取对应位置的嵌套子列表,第i行取explode1、explode2列的第i个嵌套元素
- 第二步用pandas内置的
explode方法同时展开两列,如需和示例输出一致保留单个元素的列表格式,最后做简单的格式处理即可
完整可运行代码:
import pandas as pd # 原始数据 ex = [{"A": "Germany", "word": "Danke", "explode1": [["berlin", "frankfurt"], ["Paris"], ["London", "Glassgow"]], "explode2": [["food", "cars"], ["fashion"], ["pound", "cricket"]]}, {"A": "French", "word": "merci", "explode1": [["berlin", "frankfurt"], ["Paris"], ["London", "Glassgow"]], "explode2": [["food", "cars"], ["fashion"], ["pound", "cricket"]]}, {"A": "English", "word": "Thank you", "explode1": [["berlin", "frankfurt"], ["Paris"], ["London", "Glassgow"]], "explode2": [["food", "cars"], ["fashion"], ["pound", "cricket"]]}] df = pd.DataFrame(ex) # 按行索引提取对应位置的子列表 df['explode1'] = df.apply(lambda row: row['explode1'][row.name], axis=1) df['explode2'] = df.apply(lambda row: row['explode2'][row.name], axis=1) # 同时展开两列,ignore_index重置行号 result = df.explode(['explode1', 'explode2'], ignore_index=True) # 若需要保持输出为单个元素的列表格式,添加以下两行代码即可 result['explode1'] = result['explode1'].map(lambda x: [x]) result['explode2'] = result['explode2'].map(lambda x: [x]) print(result)
代码说明:
row.name取的是当前行的索引编号,刚好和你需要提取的子列表位置一一对应,不需要额外新增索引列。
运行后输出结果和你要求的格式完全一致。
内容的提问来源于stack exchange,提问作者Dawn.Sahil
相关产品推荐
相关产品推荐

