首页 > 解决方案 > 当我使用 imputer=imputer.fit(X[:, 1:3]) ValueError: could not convert string to float 时出现错误:

问题描述

所以我正在对数据进行预处理(用平均值填充缺失值),以下是代码

注意:昨天它工作正常..今天给我这个错误

执行 imputer=imputer(x[:,1:3]) 时出现以下错误

    imputer = imputer.fit(X[:, 1:3])
Traceback (most recent call last):

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

  File "C:\Users\super\Anaconda3\lib\site-packages\sklearn\preprocessing\imputation.py", line 158, in fit
    force_all_finite=False)

  File "C:\Users\super\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 527, in check_array
    array = np.asarray(array, dtype=dtype, order=order)

  File "C:\Users\super\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 501, in asarray
    return array(a, dtype, copy=False, order=order)

ValueError: could not convert string to float: 

以下是数据

Country Age Salary  Purchased
France  44  72000   No
Spain   27  48000   Yes
Germany 30  54000   No
Spain   38  61000   No
Germany 40      Yes
France  35  58000   Yes
Spain       52000   No
France  48  79000   Yes
Germany 50  83000   No
France  37  67000   Yes

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values

# Taking care of missing data
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = np.nan, strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])</code>

`

标签: pythonvalueerror

解决方案


SimpleImputer 的工作方式与旧的 Imputer 类似;只需导入并使用它。Imputer 不再使用。试试这个代码:

from sklearn.impute import SimpleImputer

imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean',verbose=0)
imputer = imputer.fit(X[:, 1:3])

X[:, 1:3] = imputer.transform(X[:, 1:3])

推荐阅读