我想对分类变量进行编码而不对缺失值进行编码。目前,我找不到正确的解决方案,这是我的代码:
# To define my df :
df = pd.DataFrame({'A': ['X', np.NaN, 'Z'], 'B': ['DB', 'AB', 'CA'], 'C': ['KH', 1, np.NaN]})
df :
A B C
0 X DB KH
1 NaN AB 1
2 Z CA NaN
# To encoding juste A variable :
Le = preprocessing.LabelEncoder()
target = Le.fit_transform(df['A'].astype(str))
# but this method also encodes NAN values
# then I tried another handle but it does not work:
Le = preprocessing.LabelEncoder()
# define the values of A not null and try again labelencoding:
Anotnull = df.loc[df['A'] != np.nan]
target = Le.fit_transform(Anotnull.astype(str))
目标是在不触及NaN值的情况下进行标签编码
答案 0 :(得分:1)
因此,从技术上讲,这不是标签编码“不触碰Nan”,但会留下标签编码的数据框,而Nans仍在原始位置。
df_raw = pd.DataFrame({"feature1": ["a", "b", "c", np.nan, "e"],
"feature2": ["h", "i", np.nan, "k", "l"]})
# 1st possibility
df_temp = df_raw.astype("str").apply(LabelEncoder().fit_transform)
df_final = df_temp.where(~df_raw.isna(), df_raw)
# 2nd possibility
df_temp = df_raw.astype("category").apply(lambda x: x.cat.codes)
df_final = df_temp.where(~df_raw.isna(), df_raw)