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

如何将DataFrame的mpg列切片为二维数组?解决维度报错

解决sklearn线性回归"Expected 2D, got 1D array instead"报错

问题根源

你用data.iloc[:, 0].values提取的mpg列是一维数组(形状为(样本数,)),但sklearn的LinearRegression.fit()要求特征矩阵X必须是二维数组(形状为(样本数, 特征数),单特征场景下为(样本数,1))。另外你写错了train_test_split的返回值顺序,这也会引发后续错误。

三种修改方法将X转为二维数组

  • 方法1:切片时保留二维结构
    把索引从0改成[0],切片结果会是DataFrame而非Series,转成values后即为二维数组:

    X = data.iloc[:, [0]].values  # 注意方括号内是列表[0]
    
  • 方法2:用reshape转换维度
    对一维数组调用reshape(-1,1),-1让numpy自动计算样本数量,1指定列数:

    X = data.iloc[:, 0].values.reshape(-1, 1)
    
  • 方法3:用numpy的newaxis增加维度
    先导入numpy,通过[:, np.newaxis]给数组新增一个维度:

    import numpy as np
    X = data.iloc[:, 0].values[:, np.newaxis]
    

修正train_test_split的返回顺序

原代码中train_test_split的返回值顺序错误,正确顺序应为X_train, X_test, y_train, y_test,修改后:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

完整修正后代码示例

# 数据处理
data = df1.drop(df1.columns[[1, 3]], axis=1)
# 提取mpg列作为二维特征矩阵X
X = data.iloc[:, [0]].values
y = data.iloc[:, :-1].values

# 拆分数据集(修正顺序)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# 模型训练
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:50:26