在数据框的列中查找列表的任何单词
Find any word of a list in the column of dataframe
我有一个包含 4783 个元素的单词列表 negative
。我想使用下面的代码
tweets3 = tweets2[tweets2['full_text'].str.contains('|'.join(negative))]
但是,它给出了这样的错误 error: multiple repeat at position 4193
。
我不明白这个错误。显然,如果我在 str.contains
中使用单个词,例如 str.contains("deal")
,我就能得到结果。
我只需要一个新的数据框,它只包含那些包含数据框 tweets2
列 full_text
.
中出现的任何单词的行
作为一个选择,我还想看看我是否可以有一个 boolean
列来表示当前值和不存在的值,如 0 or 1
.
我在@wp78de 的帮助下使用了以下代码:
tweets2['negative'] = tweets2.loc[tweets2['full_text'].str.contains(r'(?:{})'.format('|'.join(negative)), regex=True, na=False)].copy()
对于其中可能包含正则表达式元字符的任意文字字符串,您可以使用 re.escape()
函数。沿着这条线的东西应该足够了:
.str.contains(r'(?:{})'.format(re.escape('|'.join(words)), regex=True, na=False)]
我有一个包含 4783 个元素的单词列表 negative
。我想使用下面的代码
tweets3 = tweets2[tweets2['full_text'].str.contains('|'.join(negative))]
但是,它给出了这样的错误 error: multiple repeat at position 4193
。
我不明白这个错误。显然,如果我在 str.contains
中使用单个词,例如 str.contains("deal")
,我就能得到结果。
我只需要一个新的数据框,它只包含那些包含数据框 tweets2
列 full_text
.
作为一个选择,我还想看看我是否可以有一个 boolean
列来表示当前值和不存在的值,如 0 or 1
.
我在@wp78de 的帮助下使用了以下代码:
tweets2['negative'] = tweets2.loc[tweets2['full_text'].str.contains(r'(?:{})'.format('|'.join(negative)), regex=True, na=False)].copy()
对于其中可能包含正则表达式元字符的任意文字字符串,您可以使用 re.escape()
函数。沿着这条线的东西应该足够了:
.str.contains(r'(?:{})'.format(re.escape('|'.join(words)), regex=True, na=False)]