Python中出现‘float‘ object has no attribute ‘strip‘的解决方式

在处理CSV文件时遇到'float' object has no attribute 'strip'的错误。问题在于尝试对浮点数应用strip方法。解决方案是在读取文件后使用astype(str)将数据转换为字符串类型。修改后的代码在运行时成功避免了该错误,确保了内容前后空白的正确去除和文本长度的有效统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中出现’float’ object has no attribute 'strip’的解决方式

我的原代码是这样的

document = pd.read_csv("sample_data.csv",encoding="utf-8")
#document.columns  = ['sentences'] # 重命名列名
document['公众号文章内容'] = document['公众号文章内容'].apply(lambda x: x.strip()) # 去除文章内容前后的空白
document['文章标题'] = document['文章标题'].apply(lambda x: x.strip()) # 去除文章标题前后的空白
document['lens'] = document['公众号文章内容'].apply(len) # 统计文本长度
document = document[document['lens']>1] # 去除文本长度小于等于1的文本
document.index = np.arange(len(document))

运行后出现了这样的错误:
在这里插入图片描述
解决方法:
可以在打开文件的后面加上.astype(str)就可

document = pd.read_csv("sample_data.csv",encoding="utf-8").astype(str)

在运行错误就没有了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值