获取带掩码的二维NumPy数组中特定值的位置
我需要一些帮助,想找出一个二维数组中所有符合特定条件的值(坐标)。
我之前问过类似的问题,但这次我屏蔽了一些我不感兴趣的特定值……上次,有人建议我使用 zip(*np.where(test2D < 5000.))
。
举个例子:
import numpy as np
test2D = np.array([[ 3051.11, 2984.85, 3059.17],
[ 3510.78, 3442.43, 3520.7 ],
[ 4045.91, 3975.03, 4058.15],
[ 4646.37, 4575.01, 4662.29],
[ 5322.75, 5249.33, 5342.1 ],
[ 6102.73, 6025.72, 6127.86],
[ 6985.96, 6906.81, 7018.22],
[ 7979.81, 7901.04, 8021. ],
[ 9107.18, 9021.98, 9156.44],
[ 10364.26, 10277.02, 10423.1 ],
[ 11776.65, 11682.76, 11843.18]])
这样我就能找到所有小于5000的坐标:
positions=zip(*np.where(test2D < 5000.))
现在我想排除一些对我来说没用的值(这是一个坐标数组):
rejectedvalues = np.array([[0, 0], [2, 2], [3, 1], [10, 2]])
i, j = rejectedvalues.T
mask = np.zeros(test2D.shape, bool)
mask[i,j] = True
m = np.ma.array(test2D, mask=mask)
positions2=zip(*np.where(m < 5000.))
但是 positions2 给我的结果和 positions 一样……
1 个回答
1
np.ma.where 这个函数会考虑到“掩码”,也就是说,它不会返回那些被掩盖的条件下的索引(比如 m < 5000.
这个条件)。
In [58]: np.asarray(np.column_stack(np.ma.where(m < 5000.)))
Out[58]:
array([[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 0],
[2, 1],
[3, 0],
[3, 2]])
再来看看用 np.where
这个函数的类似表达方式:
In [57]: np.asarray(np.column_stack(np.where(m < 5000.)))
Out[57]:
array([[0, 0],
[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 0],
[2, 1],
[2, 2],
[3, 0],
[3, 1],
[3, 2]])