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

Python中DataFrame分类数据转换报错:'DataFrame'无属性'i'的解决方法

问题解决:DataFrame分类数据转换报错处理

错误原因

你写的dfTrain.i是尝试访问DataFrame名为i的属性,但这里i是循环变量,代表列表里的列名,应该用方括号索引dfTrain[i]来动态获取对应列。.只能访问固定名称的列,无法用变量代替,所以才会触发'DataFrame' object has no attribute 'i'的错误。

修正后的代码

import pandas as pd

CATEGORICAL_COLUMNS = ['sex','n_siblings_spouses', 'parch', 'class',
               'embark_town', 'alone']
for i in CATEGORICAL_COLUMNS:
  dfTrain[i] = pd.factorize(dfTrain[i])[0]
dfTrain.head()

补充优化方案

如果想更简洁地批量处理,可以用apply方法:

dfTrain[CATEGORICAL_COLUMNS] = dfTrain[CATEGORICAL_COLUMNS].apply(lambda x: pd.factorize(x)[0])

内容的提问来源于stack exchange,提问作者Cole Hendrickson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:57:05