预处理数据时imputer.fit中的错误

时间:2019-04-09 02:07:20

标签: python-3.x

Python 3.6.7 IPython 7.4.0 导航器/间谍

嗨,我在使用此代码时得到TypeError: '(slice(None, None, None), slice(1, 3, None))' is an invalid key

#Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#Importing the Dataset

dataset = pd.read_csv("Data.csv")

#Independant & Dependant Variables

X = dataset.iloc[: , :-1]
Y = dataset.iloc[: , 3]

#Missing Data

from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values = np.nan, strategy = "mean", 
                        fill_value=None, verbose=0, copy=True)
imputer = imputer.fit(X[: , 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])

我得到的错误是:

from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values = np.nan, strategy = "mean", 
                        fill_value=None, verbose=0, copy=True)
imputer = imputer.fit(X[: , 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
Traceback (most recent call last):

  File "<ipython-input-4-a1bcee2e6448>", line 4, in <module>
    imputer = imputer.fit(X[: , 1:3])

  File "C:\Users\Farouk\Anaconda3\lib\site-packages\pandas\core\frame.py", 
line 2927, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\Farouk\Anaconda3\lib\site- 

packages \ pandas \ core \ indexes \ base.py“,第2657行,位于get_loc         返回self._engine.get_loc(key)

  File "pandas/_libs/index.pyx", line 108, in 
pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 110, in 
pandas._libs.index.IndexEngine.get_loc

TypeError: '(slice(None, None, None), slice(1, 3, None))' is an invalid 
key

有人知道为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

SimpleImputer的{​​{1}}功能期望narray而不是fit_transform

pandas.DataFrame

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html