首页 > 解决方案 > 如何使用 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()。我该如何解决这个问题?

标签: pythonpandas

解决方案


由于 True/False 对应于 1/0,因此您需要的只是从到的astype转换:boolint

df['Great'] = df["Summary"].str.contains("great", case=False, na=False).astype(int)

另请注意,我已删除该str.lower调用并添加case=Falsestr.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']
]

我已经在我的这篇文章中详细介绍了对象数据的列表推导的优点:F​​or loops with pandas - 我什么时候应该关心?


推荐阅读