python - 如何使用 Pandas 在列中搜索单词
问题描述
我有一个包含评论的熊猫数据框,我想在所有列中搜索特定单词。
df["Summary"].str.lower().str.contains("great", na=False)
这使结果为真或假,但我想创建一个新列,在相应的行中写入 1 或 0。
例如,如果评论中有“很棒”,它应该给出 1,而不是 2。我试过这个:
if df["Summary"].str.lower().str.contains("great", na=False) == True:
df["Great"] = '1'
else:
df["Great"] = '0'
它给出了这个错误:一个系列的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。我该如何解决这个问题?
解决方案
由于 True/False 对应于 1/0,因此您需要的只是从到的astype
转换:bool
int
df['Great'] = df["Summary"].str.contains("great", case=False, na=False).astype(int)
另请注意,我已删除该str.lower
调用并添加case=False
为str.contains
不区分大小写比较的参数。
另一种解决方案是小写,然后禁用正则表达式匹配以获得更好的性能。
df['Great'] = (df["Summary"].str.lower()
.str.contains("great", regex=False, na=False)
.astype(int))
最后,您还可以使用列表推导:
df['Great'] = [1 if 'great' in s.lower() else 0 for s in df['Summary']]
如果您还需要处理数字数据,请使用
df['Great'] = [
1 if isinstance(s, str) and 'great' in s.lower() else 0
for s in df['Summary']
]
我已经在我的这篇文章中详细介绍了对象数据的列表推导的优点:For loops with pandas - 我什么时候应该关心?
推荐阅读
- java - 如何验证用户提供的 android.net.Uri?
- javascript - 如何通过在 Angular 上使用 javascript 来更改样式
- git - 以合并分辨率格式显示 git diff
- ruby-on-rails - has_many 和 belongs_to 使用 ActiveRecord 会在 structure.sql 中生成 alter sql 语句吗?
- windows - 获取快捷方式的目标文件并将该文件放在新目录中
- r - 如何添加行并通过多个变量推断数据?
- c# - 如何将我的 Windows 社区模板数据网格的数据项行上的集合用作同一行上 ComboBox 列的 Itemsource?
- python - 无法在 Python 3.7 或 Python 3.8 中导入 numpy - Ubuntu 18.04
- r - 在 R 中使用 read_excel 正确解析日期
- r - 如何删除R字符串中的“\”字符?