python - 尝试从数据框中的行中删除停用词的属性错误
问题描述
我正在尝试从数据框中的行中删除停用词。不幸的是,我收到一个错误:
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
。在降低和/或拆分之前。
你能看看吗?谢谢您的帮助。
解决方案
好吧,无论如何,在使用 pandas 时,您都应该避免编写 for 循环。这可以在列表理解中完成。但我猜的数据类型df['Quotes']
不是字符串,而是浮点数。您可以在应用调用之前将该列转换为字符串。
df['Quotes'] = df['Quotes'].astype(str)
pandas 系列的 str 方法仅适用于 Objects(字符串,由 Pandas 定义)。这不适用于浮点类型,因此会出现错误。此外,您不必要地为每行生成停用词。这是非常低效的(因为每行调用 apply)。在函数外生成停用词语料库。此外,请查看可能适用于此处的矢量化字符串函数。
推荐阅读
- bash - 如何加快为列表中的每个条目生成 jvm 并关闭的 for 循环?
- logstash - 删除 Logstash 配置文件中不需要的字段
- xml - 在 Angular 2+ 中渲染 XML
- visual-studio - LNK1112:模块机器类型“x64”与目标机器类型“x86”冲突-opencv 构建
- javascript - JS 中的这些参数是什么?
- r - 如何在多条件下在 R 中绘制 3D
- java - 使用 Java8 Stream 从列表或集合中查找最高值
- swift - Swift AppleScript 内存泄漏
- php - 仅当从程序内启动 xampp 服务器时才返回问号而不是阿拉伯字符
- java - 有没有办法使用 selenium 和 java 从控制台设置中启用保留日志来午餐 ChromeDriver?