首页 > 解决方案 > 尝试从数据框中的行中删除停用词的属性错误

问题描述

我正在尝试从数据框中的行中删除停用词。不幸的是,我收到一个错误:

AttributeError: 'float' object has no attribute 'str'

由于

----> 8     for i in text.str.lower().split():

从代码

import nltk
from nltk.corpus import stopwords

def remove_stopwords(text):
stop_words = stopwords.words('english')
fresh_text = []

for i in text.str.lower().split():
    if i not in stop_words:
        fresh_text.append(i)

return(' '.join(fresh_text))

df['text'] = df['Quotes'].apply(remove_stopwords)

我发现这个问题应该能够解决这个问题:

如何解决属性错误'float'对象在python中没有属性'split'?

但我可能在添加时犯了一些错误str。在降低和/或拆分之前。

你能看看吗?谢谢您的帮助。

标签: pythonpandas

解决方案


好吧,无论如何,在使用 pandas 时,您都应该避免编写 for 循环。这可以在列表理解中完成。但我猜的数据类型df['Quotes']不是字符串,而是浮点数。您可以在应用调用之前将该列转换为字符串。

df['Quotes'] = df['Quotes'].astype(str)

pandas 系列的 str 方法仅适用于 Objects(字符串,由 Pandas 定义)。这不适用于浮点类型,因此会出现错误。此外,您不必要地为每行生成停用词。这是非常低效的(因为每行调用 apply)。在函数外生成停用词语料库。此外,请查看可能适用于此处的矢量化字符串函数。


推荐阅读