python - 高级布尔索引
问题描述
我想通过掩码选择值并使用掩码数组更改值。
代码:
import numpy as np
a = np.zeros((2, 2), dtype=(np.uint8, 3))
x = np.arange(4, dtype=int).reshape((2, 2))
mask = np.logical_and(a1 < 3, a1 > 0)
a[mask] = (1, x[mask], 2)
我想要结果:
a[mask]
>> [[1, 1, 2], [1, 2, 2]]
但我得到错误:
ValueError: setting an array element with a sequence.
a[mask] = (1, 2, 2)
如果尝试做数组之类的事情
[[[0, 0, 0],
[1, 2, 2]],
[[1, 2, 2],
[0, 0, 0]]]
但我需要使用 x 的值。让它看起来像
[[[0, 0, 0],
[1, 1, 3]],
[[1, 2, 3],
[0, 0, 0]]]
我该怎么做?
解决方案
可以分两步完成。
import numpy as np
a = np.zeros((2, 2), dtype=(np.uint8, 3))
x = np.arange(4, dtype=int).reshape((2, 2))
a1 = x # Create an a1 for the mask
mask = np.logical_and(a1 < 3, a1 > 0)
a[mask] = (1, 0, 2) # Set the outer columns
a[mask, 1] = x[mask] # Set the column 1
print( a )
# [[[0 0 0]
# [1 1 2]]
# [[1 2 2]
# [0 0 0]]]
推荐阅读
- join - 将两个列表中的行与一个列表中的通配符匹配
- typescript - 打字稿,从us币到es币
- dolphindb - 如何在 dolphindb 中以交互方式取消任务
- linux - 如何使用终端更改 Linux 上的 git 帐户?
- r - R 鼠标功能不应用自定义预测矩阵
- android - 如何使用 inSampleSize() 和 inJustDecodeBounds() 从 MediaStore 解码位图
- git - 选择分支来构建 Jenkins 工作的最新更改
- angular - 在离子搜索框中设置去抖动,角度不起作用
- python-3.x - 如何将 pandas.assign 与 lambda 和 if 条件一起使用
- javascript - 数据表中的 PHP 重定向按钮不起作用