首页 > 解决方案 > 如何使用 KNN 估算缺失值

问题描述

我正在尝试从我的数据框中估算缺失值,为此我使用了 fancyimpute 库。

from fancyimpute import KNN 
X_filled_knn = KNN(k=3).complete(df_OppLine[['family']])

我有这个错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-28-8475f35fc36a> in <module>()
----> 1 X_filled_knn = KNN(k=3).complete(df_OppLine[['family']])

AttributeError: 'KNN' object has no attribute 'complete'

有什么想法可以帮助我解决此错误吗?

标签: pythonpython-3.ximputation

解决方案


首先,您必须将字符串转换为数字数据。

尝试 one-hot 编码(为每个类别创建一个列,值仅为相应类别的 1,其余为 0)。您也可以尝试序数编码。它为每个类别分配一个值

from sklearn.preprocessing import OrdinalEncoder

# Create Ordinal encoder
initialize_encoder=OrdinalEncoder()

# Select non-null values of family column
family=df_OppLine["family"]
family_not_null=family[family.notnull()]

# Reshape family_not_null to shape (-1, 1)
reshaped_vals=family_not_null.values.reshape(-1,1)

# Ordinally encode reshaped_vals
encoded_vals=initialize_encoder.fit_transform(reshaped_vals)

# Assign back encoded values to non-null values 
df_OppLine.loc[family.notnull(),"family"]=np.squeeze(encoded_vals)

推荐阅读