如何将掩码从数组应用于numpy中的另一个矩阵 [英] How to apply mask from array to another matrix in numpy

查看:87
本文介绍了如何将掩码从数组应用于numpy中的另一个矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在numpy中应用蒙版以获取此输出?

How you I apply a mask in numpy to get this output?

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]

-适用于ar3 = 1的情况:ar2/ar2[:,0][:, np.newaxis]

--apply where ar3 = 1: ar2/ar2[:,0][:, np.newaxis]

-适用于ar3 = -1的情况:ar2/ar2[:,4][:, np.newaxis]

--apply where ar3 = -1: ar2/ar2[:,4][:, np.newaxis]

我追求的结果是:

[[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]]

我尝试了np.where()

推荐答案

我不明白为什么np.where在这里不起作用:

I don't see why np.where shouldn't work here:

>>> 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]])

我正在使用Python 3,这就是为什么我使用//(底数除法)而不是常规除法(/)的原因,否则结果将包含浮点数.

I'm using Python 3 that's why I used // (floor division) instead of regular division (/) otherwise the result would contain floats.

这会急切地计算数组,因此会为所有值求ar2 // ar2[:, [0]] ar2 // ar2[:, [4]].有效地将3个大小为ar2的数组保存在内存中(结果和两个临时变量).如果要提高内存效率,则需要在执行操作之前应用遮罩:

This computes the arrays eagerly, so it evaluates ar2 // ar2[:, [0]] and ar2 // ar2[:, [4]] for all values. Effectively holding 3 arrays of the size of ar2 in memory (the result and the two temporaries). 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).

这篇关于如何将掩码从数组应用于numpy中的另一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆