簡體   English   中英

如何將`str.contains`的輸出分配給Pandas列?

[英]How do I assign the output of a `str.contains` to a Pandas column?

這必須在其他地方得到解答,但我找不到鏈接。 我有一個帶有一些任意文本的df和一個單詞W的列表。 我想為df分配一個新列,使其包含W匹配的單詞。 例如,給定df

   T
   dog
   dog and meerkat
   cat

如果W =“狗”,那么我想擁有

   T
   dog                dog
   dog and meerkat    dog
   cat

到目前為止我所擁有的是什么

df[df.T.str.contains('|'.join(W), case=False)]

但這只給了我匹配的行,即:

   T
   dog
   dog and meerkat

任何想法,指針?

你可以使用Series.where - 哪里不匹配得到NaN

W = 'dog'
df['new'] = df['T'].where(df['T'].str.contains('|'.join(W), case=False))
print (df)
                 T              new
0              dog              dog
1  dog and meerkat  dog and meerkat
2              cat              NaN

或者DataFrame.loc

W = 'dog'
df.loc[df['T'].str.contains('|'.join(W), case=False), 'new'] = df['T']
print (df)
                 T              new
0              dog              dog
1  dog and meerkat  dog and meerkat
2              cat              NaN

另一種可能的解決方案是numpy.where如果不匹配,可以在其中添加值:

W = 'dog'
df['new'] = np.where(df['T'].str.contains('|'.join(W), case=False), df['T'], 'nothing')
print (df)
                 T              new
0              dog              dog
1  dog and meerkat  dog and meerkat
2              cat          nothing

但是如果只需要匹配列表使用extract值,對於groups添加first和last ()

W = ['dog', 'rabbit']
df['new'] = df['T'].str.extract('('+'|'.join(W) + ')', expand=True)
print (df)
                 T  new
0              dog  dog
1  dog and meerkat  dog
2              cat  NaN

在文檔中提取

外箱思考

布爾數組點積與單詞數組

df['T'].str.contains('dog')[:, None].dot(pd.Index(['dog']))

df.assign(new=df['T'].str.contains('dog')[:, None].dot(pd.Index(['dog'])))

                    T  new
0                 dog  dog
1     dog and meerkat  dog
2                 cat     

暫無
暫無

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

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