查找两个列表列之间的公共元素?

假设这是我的数据框:


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)


慕仙森
浏览 112回答 2
2回答

胡子哥哥

您可以尝试np.intesect1d:dw['new'] = [np.intersect1d(x,y) for x,y in zip(dw.first_item, dw.second_item)]

Helenr

尝试这个list1_as_set = set(list1)intersection = list1_as_set.intersection(list2)             intersection_as_list = list(intersection)我不确定,但试试这个!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python