【发布时间】:2018-06-03 16:16:06
【问题描述】:
我在 Google 表格中创建了下表并将其下载为 CSV 文件。
我的代码发布在下面。我真的不确定它在哪里失败。我试图逐行突出显示并运行代码,但它一直抛出该错误。
# Data Preprocessing
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import Dataset
dataset = pd.read_csv('Data2.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 5].values
# Replace Missing Values
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 1:5 ])
X[:, 1:6] = imputer.transform(X[:, 1:5])
我得到的错误是:
Could not convert string to float: 'Illinois'
我的错误消息上方也有这一行
array = np.array(array, dtype=dtype, order=order, copy=copy)
我的代码似乎无法读取包含浮点数的 GPA 列。也许我没有正确创建该列并且必须指定它们是浮动的?
*** 我正在更新完整的错误消息:
[15]: runfile('/Users/jim/Desktop/Machine Learning Class/Part 1/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/data_preprocessing_template2.py', wdir='/Users/jim/Desktop/Machine Learning Class/Part 1/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing')
Traceback (most recent call last):
File "<ipython-input-15-5f895cf9ba62>", line 1, in <module>
runfile('/Users/jim/Desktop/Machine Learning Class/Part 1/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/data_preprocessing_template2.py', wdir='/Users/jim/Desktop/Machine Learning Class/Part 1/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing')
File "/Users/jim/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "/Users/jim/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/jim/Desktop/Machine Learning Class/Part 1/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/data_preprocessing_template2.py", line 16, in <module>
imputer = imputer.fit(X[:, 1:5 ])
File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/imputation.py", line 155, in fit
force_all_finite=False)
File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py", line 433, in check_array
array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: could not convert string to float: 'Illinois'
【问题讨论】:
-
使用 X[:,2:] 作为浮点值从第 3 列开始
-
为什么不在您的问题中加入产生错误的行?
-
“我真的不确定哪里出了问题。[...] 我得到的错误是 [...]” 请包含完整的回溯(即问题中的完整错误消息)。它会告诉你代码哪里出错了。
-
嗨@WarrenWeckesser 我已经用完整的错误更新了我的帖子。谢谢。
-
@newcoder 您还没有完全粘贴错误消息。我重新创建了您的案例并运行它以查看完整的错误消息。请看我的回答。
标签: python python-3.x numpy