Python ';(切片(无,无,无),0)和#x27;是无效的密钥

Python ';(切片(无,无,无),0)和#x27;是无效的密钥,python,python-3.x,machine-learning,data-science,Python,Python 3.x,Machine Learning,Data Science,我正在编写一个代码来实现k-fold交叉验证 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

我正在编写一个代码来实现k-fold交叉验证

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      
AttributeError: 'list' object has no attribute 'iloc'  
为了解决这个问题,我尝试使用fold.iloc[I][:,0]。值等:

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
然后我得到了一个错误:

TypeError: '(slice(None, None, None), 0)' is an invalid key      
AttributeError: 'list' object has no attribute 'iloc'  
我怎样才能避开这件事

  • folds=np.array\u split(data,k)
    将返回数据帧的列表
  • 类型(折叠)=列表
  • 这就是为什么您得到了AttributeError:“list”对象没有属性“iloc”。
    List
    对象没有
    iloc
    方法
  • 所以,您需要首先使用索引访问列表,以获取每个数据帧对象<代码>折叠[i]
  • type(folds[i])==pandas.DataFrame
  • 现在在
    DataFrame
    对象上使用
    iloc
  • 折叠[i]。iloc[:,0]。值