[英]IndexError: too many indices for array , while taking care of missing data
我知道之前在 SO 上已經多次問過同樣的問題,但我真的是 Python 和機器學習的新手,在嘗試了很多次沒有結果之后,我終於把它貼在這里。 所以如果可能的話,請原諒我提出這樣的問題。
我有一個這樣的數據集,csv格式
YearsExperience Salary
1.1 39343
1.3 46205
1.5 37731
2 43525
2.2
2.9 56642
正如你在經驗 2.2 中看到的,工資數據丟失了,我試圖用均值來填充它,並執行如下操作
import numpy as np
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
#taking care of missing data
#substitue missing value with the mean
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN',strategy='mean',axis=0)
imputer = imputer.fit(y[:,0:1])
y[:,0:1] = imputer.transform(y[:,0:1]);
它給了我
IndexError: too many indices for array
但是,如果X
Like 中缺少某些東西
YearsExperience Salary
1.1 39343
1.3 46205
1.5 37731
2 43525
39891
2.9 56642
如果我執行以下操作,它會自動用mean
替換缺失值
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN',strategy='mean',axis=0)
imputer = imputer.fit(X[:,0:1])
X[:,0:1] = imputer.transform(X[:,0:1]);
您的代碼失敗的平均原因是因為y
是具有形狀的一維數組 -
X = df.iloc[:, :-1].values
y = df.iloc[:, 1].values
y.shape
(6,)
因此,在一維數組上調用y[:, 0:1]
是無效的操作 -
y[:,0:1]
IndexError: too many indices for array
相反,你應該做的是初始化y
如此 -
y = df.iloc[:, -1:].values
這將使y
成為一列的二維數組,從而解決問題。
imputer
接受具有單列的二維數組,並返回形狀相似的結果。 切片一個單列數據幀,並將其傳遞給imputer.fit_transform
,它在一個步驟中執行擬合和轉換 -
df['Salary'] = imputer.fit_transform(df[['Salary']]).ravel()
df
YearsExperience Salary
0 1.1 39343.0
1 1.3 46205.0
2 1.5 37731.0
3 2.0 43525.0
4 2.2 44689.2
5 2.9 56642.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.