假设我有这个数据框:
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
关于python - 缺失数据的 Pandas 分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53328432/