[英]How to apply mask from array to another matrix in numpy
How you I apply a mask in numpy to get this output? 我如何在numpy中应用蒙版以获取此输出?
ar2 = np.arange(1,26)[::-1].reshape([5,5]).T
ar3 = np.array([1,1,-1,-1,1])
print ar2, '\n\n', ar3
[[25 20 15 10 5]
[24 19 14 9 4]
[23 18 13 8 3]
[22 17 12 7 2]
[21 16 11 6 1]]
[ 1 1 -1 -1 1]
--apply where ar3 = 1: ar2/ar2[:,0][:, np.newaxis]
--apply,其中ar3 = 1: ar2/ar2[:,0][:, np.newaxis]
--apply where ar3 = -1: ar2/ar2[:,4][:, np.newaxis]
--apply,其中ar3 = -1: ar2/ar2[:,4][:, np.newaxis]
The result I am after is: 我追求的结果是:
[[1 0 0 0 0]
[1 0 0 0 0]
[ 7 6 4 2 1]
[11 8 6 3 1]
[1 0 0 0 0]]
I have tried np.where()
我试过np.where()
I don't see why np.where
shouldn't work here: 我不明白为什么np.where
在这里不起作用:
>>> np.where((ar3==1)[:, None],
... ar2 // ar2[:, [0]], # where condition is True, divide by first column
... ar2 // ar2[:, [4]]) # where condition is False, divide by last column
array([[ 1, 0, 0, 0, 0],
[ 1, 0, 0, 0, 0],
[ 7, 6, 4, 2, 1],
[11, 8, 6, 3, 1],
[ 1, 0, 0, 0, 0]])
I'm using Python 3 that's why I used //
(floor division) instead of regular division ( /
) otherwise the result would contain floats. 我正在使用Python 3,这就是为什么我使用//
(底数除法)而不是常规除法( /
)的原因,否则结果将包含浮点数。
This computes the arrays eagerly, so it evaluates ar2 // ar2[:, [0]]
and ar2 // ar2[:, [4]]
for all values. 这会急切地计算数组,因此会为所有值求ar2 // ar2[:, [0]]
和 ar2 // ar2[:, [4]]
。 Effectively holding 3 arrays of the size of ar2
in memory (the result and the two temporaries). 有效地将3个ar2
大小的数组保存在内存中(结果和两个临时ar2
)。 If you want it more memory-efficient you need to do apply the mask before doing the operation: 如果要提高内存效率,则需要在执行操作之前应用遮罩:
>>> res = np.empty_like(ar2)
>>> mask = ar3 == 1
>>> res[mask] = ar2[mask] // ar2[mask][:, [0]]
>>> res[~mask] = ar2[~mask] // ar2[~mask][:, [4]]
>>> res
array([[ 1, 0, 0, 0, 0],
[ 1, 0, 0, 0, 0],
[ 7, 6, 4, 2, 1],
[11, 8, 6, 3, 1],
[ 1, 0, 0, 0, 0]])
This computes only the necessary values which uses less memory (and is probably faster too). 这只会计算使用较少内存(可能也更快)的必要值。
Not the most elegant, but here's what I could think of. 不是最优雅的,但这就是我能想到的。
m = ar3 == -1
a = (ar2 // ar2[:, [0]])
a[m] = (ar2 // ar2[:, [4]])[m]
print(a)
array([[ 1, 0, 0, 0, 0],
[ 1, 0, 0, 0, 0],
[ 7, 6, 4, 2, 1],
[11, 8, 6, 3, 1],
[ 1, 0, 0, 0, 0]], dtype=int32)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.