【问题标题】:'(slice(None, None, None), 0)' is an invalid key'(slice(None, None, None), 0)' 是无效键
【发布时间】:2020-11-09 06:57:43
【问题描述】:

我正在编写代码来实现 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'  

我该如何解决这个问题?

【问题讨论】:

    标签: python python-3.x machine-learning data-science


    【解决方案1】:
    1. folds = np.array_split(data, k) 将返回 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

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2020-11-19
      • 2020-03-19
      • 1970-01-01
      • 2023-03-30
      • 2019-08-12
      • 2019-07-31
      • 1970-01-01
      • 2019-01-16
      相关资源
      最近更新 更多