I am learning how to use Imputer on Python.
This is my code:
df=pd.DataFrame([["XXL", 8, "black", "class 1", 22],
["L", np.nan, "gray", "class 2", 20],
["XL", 10, "blue", "class 2", 19],
["M", np.nan, "orange", "class 1", 17],
["M", 11, "green", "class 3", np.nan],
["M", 7, "red", "class 1", 22]])
df.columns=["size", "price", "color", "class", "boh"]
from sklearn.preprocessing import Imputer
imp=Imputer(missing_values="NaN", strategy="mean" )
imp.fit(df["price"])
df["price"]=imp.transform(df["price"])
However this rises the following error: ValueError: Length of values does not match length of index
What's wrong with my code???
Thanks for helping
Simple solution is to provide a 2D array
df=pd.DataFrame([["XXL", 8, "black", "class 1", 22],
["L", np.nan, "gray", "class 2", 20],
["XL", 10, "blue", "class 2", 19],
["M", np.nan, "orange", "class 1", 17],
["M", 11, "green", "class 3", np.nan],
["M", 7, "red", "class 1", 22]])
df.columns=["size", "price", "color", "class", "boh"]
from sklearn.preprocessing import Imputer
imp=Imputer(missing_values="NaN", strategy="mean" )
imp.fit(df[["price"]])
df["price"]=imp.transform(df[["price"]])
df['boh'] = imp.fit_transform(df[['price']])
Here is your DataFrame
Cleaned DataFrame
Here is the documentation for Simple Imputer For the fit method, it takes array-like or sparse metrix as an input parameter. you can try this :
imp.fit(df.iloc[:,1:2])
df['price']=imp.transform(df.iloc[:,1:2])
provide index location to fit method and then apply the transform.
>>> df
size price color class boh
0 XXL 8.0 black class 1 22.0
1 L 9.0 gray class 2 20.0
2 XL 10.0 blue class 2 19.0
3 M 9.0 orange class 1 17.0
4 M 11.0 green class 3 NaN
5 M 7.0 red class 1 22.0
Same way you can do for boh
imp.fit(df.iloc[:,4:5])
df['price']=imp.transform(df.iloc[:,4:5])
>>> df
size price color class boh
0 XXL 8.0 black class 1 22.0
1 L 9.0 gray class 2 20.0
2 XL 10.0 blue class 2 19.0
3 M 9.0 orange class 1 17.0
4 M 11.0 green class 3 20.0
5 M 7.0 red class 1 22.0
Kindly correct me if I am wrong. Suggestions will be appreciated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With