缺少数据的熊猫分类变量

时间:2018-11-15 21:54:42

标签: python pandas 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

1 个答案:

答案 0 :(得分:0)

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