簡體   English   中英

Python pandas 在另一列的元素列表中查找一列的元素

[英]Python pandas find element of one column in list of elements of another column

這是我的問題,我想在 dataframe 的 B 列元素列表中找到 A 列的元素。因此,我只想保留那些在 A 中找到元素的行:

df = pd.DataFrame({'A': [1, 2],
                   'B': [1, 3]
                 })
result = df[df.A.isin(df.B)]

>>> result
   A  B
0  1  1

工作正常,但我真正想要的是:

df = pd.DataFrame({'A': [1, 2],
                   'B': [[1, 2], [1, 3]]
                 })
result = df[df.A.isin(df.B)]

>>> result
Empty DataFrame
Columns: [A, B]
Index: []

哪一個不起作用,因為 A 中的元素不是與 B 列中列表的元素進行比較,而是與整個列表進行比較?

結果我想要的是:

>>> result
   A       B
0  1  [1, 2]

那可能嗎?

你可以apply

df[df.apply(lambda row: row['A'] in row['B'], axis=1)]

或 zip 理解:

df[[a in b for a,b in zip(df['A'], df['B'])]]

output:

   A       B
0  1  [1, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM