python - 当我使用 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>
`
解决方案
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])
推荐阅读
- c# - 使用 C# 的 int?[] 属性的数据注释
- c++ - 将数组传递给 V8 函数
- sql-server - 新的 SQL 安装出现安装服务错误
- r - 通过在每个组的嵌套数据中应用简单功能
- r - 在 R 编程中绘制 3D 图
- r - st_normalize.sfc(x, c(x_range[1], y_range[1], x_range[2], y_range[2])) 中的错误:域必须具有正范围
- java - 无法使用 Apache HttpClient/OkHttp 在 POST 请求中发送 .p12 文件
- r - 编写一个复杂的 curl 请求的 R 等效项
- linq - linq c# object ToDictionary
- visual-studio-2010 - 我的visual studio code集成终端很丑怎么改