python - 将数据框中列的字符串与列表中的一组单词进行比较
问题描述
我有一个包含推文的单列数据框,full_text
并且有一个negative
包含否定词的列表。我想创建一个新列,如果在推文中找到否定词1
,0
如果没有找到,则返回布尔值。
解决方案
好的,假设我们有一个这样的数据框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
推荐阅读
- jquery - 如何在 jquery ui 日期选择器中同时禁用周末和选定日期?
- r - is.data.frame(.data) 中的错误:缺少参数“.data”,没有默认值
- javascript - 使用 Django 加载 bootstrap-v5 Javascript 时出现问题
- actix-web - 没有为 `CasbinActor 实现特征`Actor`
` - php - 为什么我的 env 变量被 phpunit 忽略了?
- python - 是否可以在python中为一个参数添加多个输入
- c++ - 更有效的图像窗口/级别调整方式?C++
- javascript - JavaScript:比较两个数组并替换对象
- python - 不确定为什么在这个 if 语句中需要“继续”
- python - 使用来自用户的输入从嵌套字典中检索字典列表