如何检查df2的两列组合是否在df1列的列表中并拆分多行?
问题解决:匹配DataFrame列表与组合并展开行
示例数据
df1
A time 0 [a, b, c] 122 1 [a, d, e] 45 2 [b, c, e] 64
df2
Origin Destination 0 a b 1 b c 2 b e 3 d e
需求
检查df2中Origin与Destination的组合是否同时存在于df1的A列列表中,若存在则将该组合关联到对应行;单个列表存在多个匹配组合时,需新增行实现一行对应一个组合,最终目标结果如下:
A time Origin Destination 0 [a, b, c] 122 a b 0 [a, b, c] 122 b c 1 [a, d, e] 45 d e 2 [b, c, e] 64 b c 2 [b, c, e] 64 b e
错误代码及问题
尝试的代码:
for index, row in df1.iterrows(): row['Location'] = str(row['Location']) for index1, row1 in df2.iterrows(): row1['Origin'] = str(row1['Origin']) for index2, row2 in df2.iterrows(): row2['Destination'] = str(row1['Destination']) if row1['Origin'] and row2['Destination'] in row['Location']: df1['Origin'] = df2['Origin'] df1['Destination'] = df2['Destination']
得到错误输出(存在错误匹配,且未新增行):
Location Time Origin Destination 0 [a, b, c] 122 a b 1 [a, d, e] 45 b c 2 [b, c, e] 64 b e
代码问题分析
- 嵌套循环逻辑混乱:多次遍历df2,且错误地直接给df1整列赋值,导致结果被覆盖
- 条件判断错误:
row1['Origin'] and row2['Destination'] in row['Location']仅判断row1['Origin']非空且row2['Destination']在列表中,未检查两者是否同时存在于列表 - 未实现行展开逻辑:仅修改原df1列,无法处理多匹配时新增行的需求
正确解决方案
使用Pandas的向量化操作和行合并实现需求,避免低效的嵌套循环:
import pandas as pd # 初始化示例数据 df1 = pd.DataFrame({ 'A': [['a', 'b', 'c'], ['a', 'd', 'e'], ['b', 'c', 'e']], 'time': [122, 45, 64] }) df2 = pd.DataFrame({ 'Origin': ['a', 'b', 'b', 'd'], 'Destination': ['b', 'c', 'e', 'e'] }) # 定义函数处理df1的单行数据 def match_pairs(row): # 把当前行的列表转为集合,提升查找效率 elements = set(row['A']) # 筛选出Origin和Destination都在当前列表中的df2行 matched = df2[(df2['Origin'].isin(elements)) & (df2['Destination'].isin(elements))] if not matched.empty: # 复制当前行的A和time,与匹配的组合合并 return pd.DataFrame({ 'A': [row['A']] * len(matched), 'time': [row['time']] * len(matched), 'Origin': matched['Origin'], 'Destination': matched['Destination'] }) # 无匹配时返回空DataFrame return pd.DataFrame() # 遍历df1每行生成匹配结果,合并所有结果 final_result = pd.concat( [match_pairs(row) for _, row in df1.iterrows()], ignore_index=False # 保留原df1的索引,与目标结果一致 ) # 查看结果 print(final_result)
执行后将得到符合需求的结果,同时保留原df1的索引,实现一行多匹配时的行展开。
内容的提问来源于stack exchange,提问作者Koen van Maanen
相关产品推荐
相关产品推荐

