python - 如何使用一个 numpy bool 数组修改另一个 numpy 数组?

标签 python numpy

我有一个 bool 数组,如下所示:

arr_a = np.array(
[[False, False, False],
[True, True, True],
[True, True, True],
[False, False, False]]
)

和另一个看起来像这样的数组:

arr_b = np.array(
[[100, 100, 100],
[200, 200, 200]]
)

我正在寻找一个可以像这样调用的函数:np.boolean_combine(arr_a, arr_b),返回一个数组,用 arr_b 中的值替换 arr_a 中的 1,对于最终结果如下所示:

np.array(
[[0, 0, 0]
[100, 100, 100],
[200, 200, 200],
[0, 0, 0]]
)

有这样的功能吗?

最佳答案

您可以创建一个与 arra_b 具有相同 dtype 的新数组,使用 arr_a 获取切片 View 并从 分配值>arra_b:

out = arr_a.astype(arra_b.dtype)
out[arr_a] = arra_b.ravel()

array([[  0,   0,   0],
       [100, 100, 100],
       [200, 200, 200],
       [  0,   0,   0]])

关于python - 如何使用一个 numpy bool 数组修改另一个 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777062/

相关文章:

python - 通过python从netCDF中提取特定位置的数据

python - 为什么 PIL 生成的 JPEG 图像质量那么差?

python - numpy:高效执行数组的复杂 reshape

python - 在 python 中使用 numpy 获取避免 nan 的平均值

python - sklearn 管道中特定于列的处理

python - 读取特定字符时拆分字符串

python - 使用 python 请求模块在 AWS lambda 中进行 API post 调用时遇到问题

python - 在 matplotlib 中显示次要刻度标签时隐藏主要刻度标签

python - 有没有办法用 POSIX_FADV_DONTNEED 标志打开 hdf5 文件?