python - 缺失数据的 Pandas 分类变量

标签 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

最佳答案

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/

相关文章:

python - 仅从 pyspark 中的 Spark DF 选择数字/字符串列名称

python - 在两个 numpy 数组之间切片 pandas 行

python - str.extract 从 pandas DataFrame 的后面开始

python Pandas : How to merge based on an "OR" condition?

c - 快速排序和冒泡排序给出不同的结果

python - Pandas - 在列中的 groupby 之后连接字符串,忽略 NaN,忽略重复项

r - 多重插补中的交互项(Amelia 或其他 mi 包)

python - 将数据从 post() 传递到 get_context_data()

python - 由于组太多,Pandas 过滤器执行缓慢

python - Matplotlib 文本对齐