Pandas 具有缺失数据的分类变量

Pandas categorical variable with missing data

假设我有这个数据框:

dfdic = {"col1": ['azul', 'amarillo', 'amarillo', np.nan], "col2": [4, 5, 8, 10]}
df = pd.DataFrame(dfdic)

我想将 col1 字段转换为虚拟变量。我可以通过以下方式做到这一点:

pd.get_dummies(df, columns=['col1']).head()

这给出了

    col2    col1_amarillo   col1_azul
0   4.0     0               1
1   5.0     1               0
2   8.0     1               0
3   10      0               0

col1 中的 NaN 已被虚拟变量中的两个零替换。这是有道理的,因为它表示该实例不属于任何类别。但是,我怎样才能用 NaN 替换那些零,所以我可以

    col2    col1_amarillo   col1_azul
0   4.0     0               1
1   5.0     1               0
2   8.0     1               0
3   10      NaN             NaN

mask + isnull

您可以使用 mask 使所选列为空依赖于另一个系列。

df.iloc[:, 1:] = df.iloc[:, 1:].mask(df['col2'].isnull())

print(df)

   col2  col1_amarillo  col1_azul
0   4.0            0.0        1.0
1   5.0            1.0        0.0
2   8.0            1.0        0.0
3   NaN            NaN        NaN