[Python] KNNImputer (Python) - problem with the 'nan'

Discussão em 'Python' iniciado por Stack, Outubro 4, 2024.

  1. Stack

    Stack Membro Participativo

    I have a problem when I use KNNImputer to replace the missing values NaN of a categorical variable. The other variables besides nutrition_score_fr have no NaN. Only nutrition_scrore_fr contains 8% missing values. When I pass this code, the nan are not replaced. I just get the string nan instead of the values a, b, c, d, or e of the variable nutrition_score_fr.

    Why doesn't KNNImputer replace the NaN?

    Here is the code:

    # Convertir les catégories en entiers
    label_encoder = LabelEncoder()
    df['nutrition_grade_fr_encoded'] = label_encoder.fit_transform(df['nutrition_grade_fr'].astype(str))

    # Inclure toutes les colonnes dans l'imputation, y compris les colonnes numériques et 'nutrition_grade_fr_encoded'
    columns_to_impute = ['energy_100g', 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'salt_100g', 'sugars_100g', 'saturated-fat_100g', 'nutrition_grade_fr_encoded']

    # Imputation avec KNN
    imputer = KNNImputer(n_neighbors=5)

    # Imputation des valeurs manquantes en utilisant toutes les colonnes spécifiées
    df_imputed = imputer.fit_transform(df[columns_to_impute])

    # Convertir le résultat en DataFrame avec les mêmes colonnes
    df_imputed = pd.DataFrame(df_imputed, columns=columns_to_impute).reset_index(drop=True)

    # Reconversion de 'nutrition_grade_fr_encoded' en catégories
    df_imputed['nutrition_grade_fr'] = label_encoder.inverse_transform(df_imputed['nutrition_grade_fr_encoded'].round().astype(int))

    # 3. Réintégrer les colonnes imputées dans le DataFrame original
    df.reset_index(drop=True, inplace=True)
    df['nutrition_grade_fr'] = df_imputed['nutrition_grade_fr']


    I just get the string nan instead of the values a, b, c, d, or e of the variable nutrition_score_fr.

    Continue reading...

Compartilhe esta Página