我正在使用来自Udemy课程的csv文件进行训练。为了简单起见,我只想使用年龄和国家这两列。以下是代码:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.compose import ColumnTransformer as ctfrom sklearn.model_selection import train_test_split as ttsdata = pd.read_csv("advertising.csv")X = data[["Age","Country"]]y = data[["Clicked on Ad"]]from sklearn.preprocessing import OneHotEncodercat = X["Country"]one_hot = OneHotEncoder()transformer = ct([("one_hot", one_hot, cat)],remainder="passthrough")transformed_X = transformer.fit_transform(X)print(transformed_X)
我得到了这个错误:
runfile('C:/Users/--/.spyder-py3/untitled0.py', wdir='C:/Users/--/.spyder-py3')Traceback (most recent call last): File "C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 2895, in get_loc return self._engine.get_loc(casted_key) File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas\_libs\hashtable_class_helper.pxi", line 1683, in pandas._libs.hashtable.PyObjectHashTable.get_itemKeyError: 'Tunisia'The above exception was the direct cause of the following exception:Traceback (most recent call last): File "C:\Anaconda\lib\site-packages\sklearn\utils\__init__.py", line 447, in _get_column_indices col_idx = all_columns.get_loc(col) File "C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 2897, in get_loc raise KeyError(key) from errKeyError: 'Tunisia'The above exception was the direct cause of the following exception:Traceback (most recent call last): File "C:\Users\--\.spyder-py3\untitled0.py", line 17, in <module> transformed_X = transformer.fit_transform(X) File "C:\Anaconda\lib\site-packages\sklearn\compose\_column_transformer.py", line 529, in fit_transform self._validate_remainder(X) File "C:\Anaconda\lib\site-packages\sklearn\compose\_column_transformer.py", line 327, in _validate_remainder cols.extend(_get_column_indices(X, columns)) File "C:\Anaconda\lib\site-packages\sklearn\utils\__init__.py", line 454, in _get_column_indices raise ValueError(ValueError: A given column is not a column of the dataframe
“Tunisia”是”Country”列下的第一个国家
可能是什么导致了这个问题?
提前感谢您。
回答:
问题发生是因为您没有正确指定要转换的列。在这一行:
transformer = ct([("one_hot", one_hot, cat)],remainder="passthrough")
cat
应该代表您想要转换的列的索引或名称。然而,您传递了一个完整的数据框,因为您设置了cat = X["Country"]
。
要解决这个问题,只需使用以下选项之一:
#选项1cat = ['Country']# 选项2cat = [1]
这样应该就可以正常工作了。