python - 在 np.where() 逻辑中指定 NaN 编码

标签 python pandas dataframe numpy conditional-statements

我的数据如下所示:

    id    case2_q6
0   300   3.0
1   304   4.0
2   306   3.0
3   309   1.0
4   311   3.0
5   312   4.0
6   314   NaN
7   315   2.0
8   316   3.0
9   317   3.0

并使用此 np.where() 函数调用来生成新变量:

df['fluid_2'] = np.where((df['case2_q6'] == 1) | (df['case2_q6'] == 2), 1, 0)

现在df具有fluid_2列,如下所示:

    id    case2_q6  fluid_2
0   300   3.0       0
1   304   4.0       0
2   306   3.0       0
3   309   1.0       1
4   311   3.0       0
5   312   4.0       0
6   314   NaN       0
7   315   2.0       1
8   316   3.0       0
9   317   3.0       0

如您所见,索引 6 处的 NaN 值已转换为 0。有没有办法设置 np.where() 以便在 fluid_2 中将它们保留为 NaN 值?

期望的输出是:

    id    case2_q6  fluid_2
0   300   3.0       0
1   304   4.0       0
2   306   3.0       0
3   309   1.0       1
4   311   3.0       0
5   312   4.0       0
6   314   NaN       NaN
7   315   2.0       1
8   316   3.0       0
9   317   3.0       0

保留 NaN 的位置。

最佳答案

可能的解决方案:

df['fluid_2'] = np.where(
    df['case2_q6'].isna(), np.nan, 
    np.where((df['case2_q6'] == 1) | (df['case2_q6'] == 2), 1, 0))

另一种可能的解决方案:

df['fluid_2'] = df['case2_q6'].clip(upper=1).mul(df['case2_q6'].isin([1,2]))

输出:

    id  case2_q6  fluid_2
0  300       3.0      0.0
1  304       4.0      0.0
2  306       3.0      0.0
3  309       1.0      1.0
4  311       3.0      0.0
5  312       4.0      0.0
6  314       NaN      NaN
7  315       2.0      1.0
8  316       3.0      0.0
9  317       3.0      0.0

关于python - 在 np.where() 逻辑中指定 NaN 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75804905/

相关文章:

python - DataFrame 减去分组均值

r - 合并不同大小的数据帧

python - 我应该如何从 with 语句返回有趣的值?

python - 我无法在Python太空入侵者游戏中射击时移动我的角色(使用Zelle图形包)

Python 读取带有双引号元素和引号行的 CSV

python - 如果满足条件则添加空行 Pandas

python - reshape Pandas 数据框以反射(reflect)隐式 x 值?

python - 属性错误: 'numpy.ndarray' object has no attribute 'getA1'

python - 我的所有 Django 应用程序中都缺少 CSS 样式

Python - 统计一个列表与多个列表完全匹配的次数