簡體   English   中英

Pandas-如何檢查DF行中的字符串列表是否包含另一個DF中的任何串聯字符串?

[英]Pandas- How to check if list of strings in DF row contains any of strings in series in another DF?

我有一個DataFrame,其中一列包含字符串列表,如下所示:

print(df_1.lists)

出:

0      [Pucku, Byłam, Miruś, Funkcjonariusze]
1      [Greger, Pytam, Jana, Dopóki, Wiary]
2      [Baborowa, Chcę, Innym, Baborowie]
etc

我有另一個DataFrame,在一個系列中包含單詞:

print(df_2.check)

出:

0                   Olszany
1                    Pucków
2                  Baborowa
3                Studzionki
4                     Pytam
5                  Lasowice
etc

我想獲取每行df_1.lists並檢查列表是否包含來自df_2.check任何單詞。 如果它包含,那么我想將這些包含的單詞分配給df_1.lists的列。 怎么做?

[編輯]我試過df_1.lists.apply(lambda x:[list(set(df_2.checks.str.extract(r“(”+ i + r“)”)。dropna()。values))for i in x])但這太慢了。

使用嵌套列表理解:

df_1['new'] = [[y for y in x if y in df_2['check'].values] for x in df_1['lists']]

或者為每個值獲取set和list之間的intersection

df_1['new'] = [list(set(x).intersection(df_2['check'])) for x in df_1['lists']]

集之間的類似intersection

s = set(df_2['check'])
df_1['new'] = [list(set(x).intersection(s)) for x in df_1['lists']]

暫無
暫無

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

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