【问题标题】:ERROR: 'numpy.ndarray' object has no attribute 'iloc'错误:“numpy.ndarray”对象没有属性“iloc”
【发布时间】:2020-04-17 05:50:01
【问题描述】:

我正在尝试运行我的 K 折交叉验证,结果发生了这种情况

from sklearn import model_selection

kFold = model_selection.KFold(n_splits=5, shuffle=True)

#use the split function of kfold to split the housing data set
for trainIndex, testIndex in kFold.split(df):
    print("Fold: ",i)
    print(trainIndex.shape)
    print(trainIndex)
    i += 1

lRegPara = [0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 1]

final_results = []
i=0

for trainIndex, testIndex in kFold.split(df):


    # split the train test further
    trainX, validX, trainY, validY = train_test_split(np.array(X.iloc[trainIndex]),
                                                                      np.array(Y.iloc[trainIndex]), 
                                                                      test_size=0.20, random_state=99)

    # optimise the linear regression
    lResults = []


    for regPara in lRegPara:

        polyLassoReg = Lasso(alpha=regPara, normalize=True)

        polyFitTrainX = polyreg.fit_transform(trainX)

        polyLassoReg.fit(polyFitTrainX, trainY)

        polyFitValidX = polyreg.fit_transform(validX)

        predictKY = polyLassoReg.predict(polyFitValidX)

        mse = mean_squared_error(predictKY, validY)

        lResults.append(mse)

    final_results.append(lResults)

    plt.plot(lRegPara, lResults)

为什么?我一直收到此错误“numpy.ndarray”对象没有属性“iloc”。我到处搜索,但没有类似的问题。我在numpy中尝试了函数'loc',结果还是一样。

【问题讨论】:

    标签: jupyter-notebook


    【解决方案1】:

    将您的 numpy 数组转换为 pandas 数据帧

    df = pd.DataFrame({'column0': numpy_array[:, 0], 
                       'column1': numpy_array[:, 1], 
                       'column2': numpy_array[:, 2],
                       'column3': numpy_array[:, 3],
                       'column4': numpy_array[:, 4] })
    

    然后你就可以使用 iloc 和其他数据框函数了

    【讨论】:

      猜你喜欢
      • 2019-04-10
      • 2020-04-14
      • 2021-12-10
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      相关资源
      最近更新 更多