Predicting missing values with scikit-learn's

2019-03-25 00:40发布

I am writing a very basic program to predict missing values in a dataset using scikit-learn's Imputer class.

I have made a NumPy array, created an Imputer object with strategy='mean' and performed fit_transform() on the NumPy array.

When I print the array after performing fit_transform(), the 'Nan's remain, and I dont get any prediction.

What am I doing wrong here? How do I go about predicting the missing values?

import numpy as np
from sklearn.preprocessing import Imputer

X = np.array([[23.56],[53.45],['NaN'],[44.44],[77.78],['NaN'],[234.44],[11.33],[79.87]])

print X

imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit_transform(X)

print X

2条回答
看我几分像从前
2楼-- · 2019-03-25 01:17

As the new array is returned from the transform function, therefore, I have to store it in the same array (X) to alter the values

 from sklearn.preprocessing import Imputer
 imputer = Imputer(missing_values='NaN',strategy='mean',axis=0)  
 imputer = imputer.fit(X[:,1:3])
 X[:,1:3]= imputer.transform(X[:,1:3])
查看更多
虎瘦雄心在
3楼-- · 2019-03-25 01:28

Per the documentation, sklearn.preprocessing.Imputer.fit_transform returns a new array, it doesn't alter the argument array. The minimal fix is therefore:

X = imp.fit_transform(X)
查看更多
登录 后发表回答