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

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

Pandas 列表列,檢查列表是否相交

Pandas 列表列,檢查列表是否相交

波斯汪 2023-07-18 18:00:20
我有一個名為 的數據框,a其結構如下:df = pd.DataFrame({    'id': [1, 2, 3],    'numbers_a': [[2, 3, 5], [1, 2, 4], [4, 6, 9]],    'numbers_b': [[2, 1, 3], [10, 11], [4, 5, 7]]})df| id | numbers_a | numbers_b ||----|-----------|-----------|| 1  | [2, 3, 5] | [2, 1, 3] || 2  | [1, 2, 4] | [10, 11]  || 3  | [4, 6, 9] | [4, 5, 7] | 我想向該數據框添加一個名為 的新列,如果 中的任何一個值在中result,則應該是該列。因此,以下應該是結果數據框:TRUEnumbers_bnumbers_a| id | numbers_a | numbers_b | result ||----|-----------|-----------|--------|| 1  | [2, 3, 5] | [2, 1, 3] | TRUE   || 2  | [1, 2, 4] | [10, 11]  | FALSE  || 3  | [4, 6, 9] | [4, 5, 7] | TRUE   | 我嘗試使用以下代碼片段,但所有值都為 FALSE:a['result'] = pd.DataFrame(a.numbers_b.tolist()).isin(a.numbers_a).any(1).astype(bool)我該如何解決這個問題?提前致謝。
查看完整描述

1 回答

?
慕無忌1623718

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

嘗試設置交集:


df['numbers_a'].map(set) & df['numbers_b'].map(set)


0     True

1    False

2     True

dtype: bool

這對于重載的 pandas 布爾運算符效果很好,盡管它的性能不是特別好。


另一種方法涉及列表理解:


[set(a).intersection(b) for a, b in zip(df['numbers_a'], df['numbers_b'])]

# [True, False, True]


# To assign the result back

df['result'] = [

    set(a).intersection(b) for a, b in zip(df['numbers_a'], df['numbers_b'])]


查看完整回答
反對 回復 2023-07-18
  • 1 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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