首页 > 解决方案 > 将数据框中列的字符串与列表中的一组单词进行比较

问题描述

我有一个包含推文的单列数据框,full_text并且有一个negative包含否定词的列表。我想创建一个新列,如果在推文中找到否定词10如果没有找到,则返回布尔值。

标签: pythonpandascomparetweets

解决方案


好的,假设我们有一个这样的数据框data和列表negative_words

data = pd.DataFrame({
    'Tweets' : ['This is bad', 'This is terrible', 'This is good', 'This is great'],
})

negative_words = ['bad', 'terrible']

然后我们可以做类似的事情:

1)我们可以使用一个lambda函数any

# create lambda with any:
data['Negative'] = data.apply(lambda x: True if any(word in x.Tweets for word in negative_words) else False, axis=1)

并且会得到:

             Tweets  Negative
0       This is bad      True
1  This is terrible      True
2      This is good     False
3     This is great     False

推荐阅读