'(slice(None, None, None), 0)' 是无效键

'(slice(None, None, None), 0)' is an invalid key

我正在编写代码来实现 k 折交叉验证。

data = pd.read_csv('Data_assignment1.csv')
k=10

np.random.shuffle(data.values)  # Shuffle all rows
folds = np.array_split(data, k) # split the data into k folds

for i in range(k):
    x_cv = folds[i][:, 0]  # Set ith fold for testing
    y_cv = folds[i][:, 1]
    new_folds = np.row_stack(np.delete(folds, i, 0)) # Remove ith fold for training
    x_train = new_folds[:, 0]  # Set the remaining folds for training
    y_train = new_folds[:, 1]

尝试设置 x_cv 和 y_cv 的值时,出现错误:

TypeError: '(slice(None, None, None), 0)' is an invalid key      

为了解决这个问题,我尝试使用 folds.iloc[i][:, 0].values 等:

for i in range(k):
    x_cv = folds.iloc[i][:, 0].values  # Set ith fold for testing
    y_cv = folds.iloc[i][:, 1].values
    new_folds = np.row_stack(np.delete(folds, i, 0)) # Remove ith fold for training
    x_train = new_folds.iloc[:, 0].values  # Set the remaining folds for training
    y_train = new_folds.iloc[:, 1].values

然后我得到了错误:

AttributeError: 'list' object has no attribute 'iloc'  

我该如何解决这个问题?

  1. folds = np.array_split(data, k) 会 return 一个 list of Dataframes.
  2. type(folds) == list
  3. 这就是您获得 AttributeError: 'list' object has no attribute 'iloc' 的原因。 List 对象没有 iloc 方法。
  4. 所以你需要先访问带有索引的列表来获取每个DataFrame对象。 folds[i].
  5. type(folds[i]) == pandas.DataFrame
  6. 现在在 DataFrame 对象上使用 iloc
  7. folds[i].iloc[:,0].values