【发布时间】:2021-01-01 19:09:18
【问题描述】:
假设这是我拥有的数据框:
dw = {'id' : [1,2,3,4,5], 'first_item' : [['Motherboard', 'Miscellaneous'],
['Miscellaneous', 'Mechanical Hardware'],
['Motherboard', 'Hard Drive'],
['Mechanical Hardware', 'Hard Drive'],
['Motherboard','Mechanical Hardware']],
'second_item' : [['Motherboard', 'Hard Drive'],
['Mechanical Hardware', 'Mechanical Hardware'],
['Motherboard', 'Hard Drive'],
['Mechanical Hardware', 'Hard Drive'],
['Motherboard','Miscellaneous']]}
dw = pd.DataFrame(dw)
我想找到第一项和第二项(按行)之间的交集/公共元素,得到这样的输出:
dw['new']
1 ['Motherboard']
2 ['Mechanical Hardware']
3 ['Motherboard', 'Hard Drive']
4 ['Mechanical Hardware', 'Hard Drive']
5 ['Motherboard']
我尝试了下面的代码,但它没有产生预期的结果:
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
dw['new'] = dw.apply(lambda x: intersection(dw.first_item, dw.second_item), axis = 1)
【问题讨论】:
-
是的。那是一个错误(错字)。感谢您的强调。但我收到一个错误:不可散列的类型:'list'。
-
是的。它现在起作用了。我意识到错误在哪里。非常感谢。你能帮我找到不常见的元素吗?即消除第一项和第二项中未共享的公共/交叉元素和查找元素?
-
您正在寻找对称差异。试试
list(set(lst1) ^ set(lst2))?
标签: python pandas list dataframe lambda