繁体   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