#如果我们有一个类似列表的键,选择列时会引发_check_indexing_error

问题描述 投票:0回答:1

我正在尝试构建一个 KNearest Neighbor 系统来帮助我对距离进行分类。

原始数据框中的列包含 TotalDistance 和 Label 列。

要使用 KNN,我必须对 TotalDistance 的距离进行编码,因此我执行了以下操作:

data = pd.read_excel('/content/training set only distance.xlsx')
target = pd.read_excel('/content/testing set only distance.xlsx')

label_enc = preprocessing.LabelEncoder()
encoded_x = label_enc.fit_transform(data['TotalDistance'])
encoded_y = label_enc.fit_transform(target['TotalDistance'])

我想将编码后的数字带回原始数据帧,因此我执行了以下操作:

data['encoded'] = encoded_x
target['encoded'] = encoded_y

X = data['label', 'encoded']
y = target['label', 'encoded']

这在 X 上给了我以下错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3801             try:
-> 3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:

4 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: ('label', 'encoded')

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:
-> 3804                 raise KeyError(key) from err
   3805             except TypeError:
   3806                 # If we have a listlike key, _check_indexing_error will raise

KeyError: ('label', 'encoded')

从研究来看,它似乎在抱怨我试图使用不正确的索引,但是当我显示数据帧的列时,编码的列存在。

Index(['TotalDistance', 'Label', 'encoded'], dtype='object')
Index(['TotalDistance', 'Label', 'encoded'], dtype='object')

我尝试将列分配给 x 和 y,如下所示:

X = data[['label', 'encoded']]
y = target[['label', 'encoded']]

但这也给了我一个错误。

我做错了什么?

python dataframe knn label-encoding
1个回答
0
投票

检查输入的标题。当从 SQL 表导入两个集合时,我得到了同样的结果。当我检查两者时,其中一个错过了第一个标题,因此没有索引键。

© www.soinside.com 2019 - 2024. All rights reserved.