我有以下 numpy 数组
A: shape (n1, n2) array of float
B: shape (n2,) array of float
M: shape (n1, n2) array of bool
如何将以下伪代码转换为高效的真实代码?数组可能很大,可能超过 1 亿个元素。
A[M] = ("B broadcast to shape (n1,n2)")[M]
我有以下 numpy 数组
A: shape (n1, n2) array of float
B: shape (n2,) array of float
M: shape (n1, n2) array of bool
如何将以下伪代码转换为高效的真实代码?数组可能很大,可能超过 1 亿个元素。
A[M] = ("B broadcast to shape (n1,n2)")[M]
Broadcasting is simple and memory efficient:
A, B, M = np.broadcast_arrays(A, B, M)
However using this B
in your code A[M] = B[M]
would not be memory efficient because B[M]
has as many real elements as M
has True
values.
Instead use:
np.putmask(A, M, B)
Since B
is repeated automatically with the putmask
function, you should not even have to broadcast it. Though I guess it cannot hurt to do that.