使用掩码插入 sklearn 迭代输入器中的值

问题描述 投票:0回答:1

我创建了一组随机缺失值来使用树输入器进行练习。但是,我一直不知道如何将缺失的值覆盖到我的数据框中。我的缺失值如下所示:

enter image description here

from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer

df_post_copy = df_post.copy()
missing_mask = df_post_copy.isna()
imputer = IterativeImputer(max_iter=10, random_state=0)
imputed_values = imputer.fit_transform(df_post_copy)
df_copy[missing_mask] = imputed_values[missing_mask]

结果:

ValueError: other must be the same shape as self when an ndarray

但是形状很配...

imputed_values.shape
(16494, 29)

类型为:

type(imputed_values)
numpy.ndarray

由于它是正确的形状,我尝试过将其转换为 pandas 数据框:

test_imputed_values = pd.DataFrame(imputed_values)

当我尝试时:

df_copy[missing_mask] = test_imputed_values[missing_mask]

我得到的与上面相同:

enter image description here

如何使用掩码在需要的地方插入估算值?

python pandas sklearn-pandas imputation
1个回答
0
投票

imputer.fit_transform(...)
同时返回原始值和缺失值。如果你想要一个更新的 DataFrame,类似

imputed_values = imputer.fit_transform(df_post_copy)
df_post_copy.loc[: :] = imputed_values

应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.