调用房价预测函数遇AttributeError:numpy.ndarray无columns属性
解决房价预测函数的AttributeError问题
问题根源
报错'numpy.ndarray' object has no attribute 'columns'的核心原因:
- 你使用了
global x声明,但在函数内部将全局变量x重新赋值为numpy数组(x = np.zeros(len(x.columns))),导致后续代码(甚至第一次调用的后续步骤)中,x已经不再是原始的DataFrame,而是没有columns属性的numpy数组,自然无法调用.columns方法。 - 另外函数名存在拼写错误:
predit_price应为predict_price(可选修正)。
修复后的代码
不要修改全局的x,改用局部变量存储特征向量,保留原始DataFrame用于获取列信息:
def predict_price(location, sqft, bath, bhk): global x # 此处x为训练模型时用的原始DataFrame,请勿修改 loc_index = np.where(x.columns == location)[0][0] # 创建局部变量存储特征向量,避免覆盖全局的x features = np.zeros(len(x.columns)) features[0] = sqft features[1] = bath features[2] = bhk if loc_index >= 0: features[loc_index] = 1 return lm.predict([features])[0]
额外优化建议
- 确保全局变量
x始终是训练时的原始DataFrame,不要在任何逻辑中把它重新赋值为数组或其他类型。 - 增加位置不存在的异常处理,避免输入未知位置时触发索引错误:
loc_indices = np.where(x.columns == location)[0] if len(loc_indices) == 0: raise ValueError(f"位置 {location} 未在训练数据中找到") loc_index = loc_indices[0]
内容的提问来源于stack exchange,提问作者user18941361
相关产品推荐
相关产品推荐

