亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

查找兩個列表列之間的公共元素?

查找兩個列表列之間的公共元素?

慕仙森 2023-08-08 15:06:07
假設這是我的數據框: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)
查看完整描述

2 回答

?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

您可以嘗試np.intesect1d

dw['new'] = [np.intersect1d(x,y) for x,y in zip(dw.first_item, dw.second_item)]


查看完整回答
反對 回復 2023-08-08
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

嘗試這個


list1_as_set = set(list1)

intersection = list1_as_set.intersection(list2)             

intersection_as_list = list(intersection)

我不確定,但試試這個!


查看完整回答
反對 回復 2023-08-08
  • 2 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號