You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何以下代码第8行会出现TypeError: 'Float'对象不可迭代错误?

分析 TypeError: 'Float' object is not iterable 错误原因

Hey there! Let's break down exactly why this error pops up when your code hits line 8.

错误核心定位

The error originates directly in your mapper lambda function:

mapper = lambda x: sum([ord(digit) for digit in x])

When this function runs, you’re trying to iterate over x (with for digit in x), but x is a Float object—and floats aren’t iterable. Unlike strings or lists, you can’t loop through a single floating-point number character by character.

为什么x会是浮点数?

Your code assumes any column with cardinality > 2 is a categorical column (filled with string values), but that’s not the case here. The column you’re processing actually contains floating-point numbers, not text. When x_train[column].apply(mapper) executes, it passes each float value from the column to x, and trying to loop over that float triggers the TypeError.

快速修复与优化建议

  • 先转成字符串再处理: 修改mapper函数,先把浮点数转换成字符串,这样就能正常遍历字符了:
    mapper = lambda x: sum([ord(digit) for digit in str(x)])
    
  • 校验列类型判断逻辑: 仔细检查高基数列是否真的是分类列。有些高基数列可能是连续数值型,这种ASCII码求和的处理方式对它们来说毫无意义。
  • 修复列删除逻辑: 你当前的删除代码并没有真正从DataFrame中移除列,需要重新赋值或者使用inplace=True:
    # 方式1:重新赋值
    x_train = x_train.drop(column, axis=1)
    x_test = x_test.drop(column, axis=1)
    # 方式2:使用inplace参数
    x_train.drop(column, axis=1, inplace=True)
    x_test.drop(column, axis=1, inplace=True)
    

内容的提问来源于stack exchange,提问作者Monisha Arunkumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:32:26