[英]carving 2D numpy array by index
How do i "carve" or mask a 2D numpy array according to an index formula? 如何根据索引公式“雕刻”或掩盖2D numpy数组? I don't care what the element value is, only its position in the array. 我不关心元素值是什么,只关心它在数组中的位置。
For example, given an mxm array, how do I extract all elements whose address conforms to 例如,给定一个mxm数组,如何提取地址符合的所有元素
for i in range(0,m):
for j in range(0,m):
if j-i-k>=0:
A[i,j] = 1
elif j-p-k>=0:
A[i,j] = 1
elif i-k>=0:
A[i,j] = 1
else:
A[i,j] = 0
j=j+1
i=i+1
where 哪里
k and p are an arbitrary fences k和p是任意围栏
Assume 假设
k<m
p<m
This ends up looking like a diagonal slice + a horizontal slice + a vertical slice. 这最终看起来像对角切片+水平切片+垂直切片。 Can it be done without the for loops above? 可以在没有上面的for循环的情况下完成吗?
In [1]: import numpy as np
In [2]: k = 2
In [3]: i, j = np.ogrid[0:5,0:5]
In [4]: mask = (j-i-k < 0)
In [5]: mask
Out[5]:
array([[ True, True, False, False, False],
[ True, True, True, False, False],
[ True, True, True, True, False],
[ True, True, True, True, True],
[ True, True, True, True, True]], dtype=bool)
In [6]: mask.shape
Out[6]: (5, 5)
In [7]: mask.dtype
Out[7]: dtype('bool')
xdim,ydim = data.shape
k = 2
a, b = np.meshgrid(range(ydim),range(xdim))
mask = (b - a -k) < 0
new_data = data[mask]
new_data2 = np.array(data) # to force a copy
new_data2[~mask] = 0
new_data
is a vector because the masking processes (done this way) flattens the array. new_data
是一个向量,因为屏蔽过程(以这种方式完成)会使数组变平。 Your are selecting a shape with a ragged that cannot be represented as an array. 您正在选择一个不能用数组表示的参差不齐的形状。 If you just want to set the non-selcted values to 0, use new_data2. 如果您只想将非选择值设置为0,请使用new_data2。
Here's yet another way using np.indices
: 这是使用np.indices
的另一种方式:
>>> import numpy as np
>>> a = np.arange(90).reshape(10,9)
>>> b = np.indices(a.shape)
>>> k = 2
>>> i = b[1] - b[0] - k
>>> a[i < 0]
array([ 0, 1, 9, 10, 11, 18, 19, 20, 21, 27, 28, 29, 30, 31, 36, 37, 38,
39, 40, 41, 45, 46, 47, 48, 49, 50, 51, 54, 55, 56, 57, 58, 59, 60,
61, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.