我有一個名為 的數據框,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'])]
添加回答
舉報
0/150
提交
取消