如何使用np.where替换pandas列值时保留nan值不被修改
解决方案
你原来的代码问题在于NaN和任意数值做比较返回的结果都是False,所以所有NaN都会被np.where的第三个参数0覆盖,之前的掩码方案未生效是因为后续的普通np.where调用没有保留掩码逻辑。你可以用以下几种方法实现需求:
方法1:嵌套np.where,主动保留NaN
在最外层优先判断是否为NaN,是则保留原值,否则执行大小判断替换:
df["col"] = np.where(df["col"].isna(), df["col"], np.where(df["col"] > 2, 1, 0))
方法2:用pandas原生where方法,代码更简洁
pandas.Series.where方法会在条件为False时替换值,我们可以先保留所有NaN行,剩下的行直接通过布尔值转整数得到0/1结果:
df["col"] = df["col"].where(df["col"].isna(), (df["col"] > 2).astype("int"))
方法3:loc条件赋值,可读性最高
先筛选出非NaN的行,再分条件赋值,后续修改规则更方便:
non_na_mask = df["col"].notna() df.loc[non_na_mask & (df["col"] > 2), "col"] = 1 df.loc[non_na_mask & (df["col"] <= 2), "col"] = 0
内容的提问来源于stack exchange,提问作者user9364978
相关产品推荐
相关产品推荐

