[英]Grepl (R) function similar usage in Python
我正在尝试用 Python 编写以下代码,我已经用 R 编写了它。这很简单,但是我对 Python 非常陌生。 如果df$text 中存在任何单词(来自单词列表),我会将text列指定为 1 到pos_d列中。 任何帮助,将不胜感激。
wordlist<-list("word1|word2")
df$pos_d <- grepl(wordlist, df$text)
df$pos_d [df$pos_d == "true"] <- 1
干得好
如果 wordlist 是一个列表
df['pos_d'][(df['text'].isin(wordlist)] = 1
如果 wordlist 是一个字符串
df['pos_d'][(df['text'] in (wordlist)] = 1
享受并继续发布!
你也可以使用re
和str.contains
来做到这str.contains
:
import re
boolean_mask_rows = df['text'].astype(str).str.contains(wordlist, regex = True, case = False)
df.loc[boolean_mask_rows, 'pos_d'] = 1
以上,
在第一行中,我们根据 wordlist 中的匹配字符串与 df 中的“text”列来获取布尔向量。
在第二行中,我们使用带有loc
布尔向量索引来写 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.