Pandas 对返回的数据"不再支持将类似列表的内容传递给任何缺少标签的 .loc 或 []"train_test_split



由于某些原因,train_testrongplit,尽管长度相同,索引看起来相同,但会触发此错误。

from sklearn.model_selection import KFold
data = {'col1':[30.5,45,1,99,6,5,4,2,5,7,7,3], 'col2':[99.5, 98, 95, 90,1,5,6,7,4,4,3,3],'col3':[23, 23.6, 3, 90,1,9,60,9,7,2,2,1]} 
df = pd.DataFrame(data)
train, test = train_test_split(df, test_size=0.10)
X = train[['col1', 'col2']]
y2 = train['col3']
X = np.array(X)
kf = KFold(n_splits=3, shuffle=True)
for train_index, test_index in kf.split(X):
X_train, y_train = X[train_index], y[train_index]

y是熊猫系列(长度与x相同(。x是一个数据帧,大约有20个数字列被投射到numpy数组中。

由于某些原因,train_testrongplit会触发错误,尽管长度相同。

如果我不叫train_testrongplit,它会很好用。

最后一行由于尝试以这种方式对numpy数组进行索引而触发错误:y[train_ind]

我试图为您的情况创建一个场景。

我创建了以下数据帧:

col1  col2  col3
0      1     2     1
1      3     4     0
2      5     6     1
3      7     8     0
4      9    10     1
5     11    12     0
6     13    14     1
7     15    16     0
8     17    18     1
9     19    20     0
10    21    22     1
11    23    24     0
12    25    26     1
13    27    28     0
14    29    30     1

我为X设置col1col2,为y设置col3。之后,我将X转换为numpy数组,如下所示。唯一的区别是我在KFold中使用了shuffle

X = df[['col1', 'col2']]
y = df['col3']
X = np.array(X)
kf = KFold(n_splits=3, shuffle=True)
for train_index, test_index in kf.split(X):
X_train, y_train = X[train_index], y[train_index]

而且效果很好。所以请检查我的代码和你的代码,如果我遗漏了什么,请澄清。

更新

我假设y2是y。所以y类型仍然是Series,你需要使用.iloc。下面的代码运行得很好。

data = {'col1':[30.5,45,1,99,6,5,4,2,5,7,7,3], 'col2':[99.5, 98, 95, 90,1,5,6,7,4,4,3,3],'col3':[23, 23.6, 3, 90,1,9,60,9,7,2,2,1]}
df = pd.DataFrame(data)
train, test = train_test_split(df, test_size=0.10)
X = train[['col1', 'col2']]
y = train['col3']
X = np.array(X)
kf = KFold(n_splits=3, shuffle=True)
for train_index, test_index in kf.split(X):
X_train, y_train = X[train_index], y.iloc[train_index]

如果这对任何人都有帮助,我在数据帧上使用.groupby函数时也遇到了同样的问题。我使用修复了它

df.reset_index(drop=True, inplace=True)

最新更新