[英]Counting “holes” in a numpy 2D matrix
給定1s和0s的2D矩陣,例如-
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 1, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 1, 0, 0, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 1, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 1, 1, 1, 0],
[1, 0, 0, 0, 1, 1, 0, 1, 1, 0]])
我希望計算某些統計數據:
1. Number of holes (no. of 0s with at least one 1 above): 12
2. Sum of hole depths (no. of 1s above holes, summed across columns): 0+3+(1+1)+1+0+3+(2+8)+(2+1)+(1+1)+3 = 27
3. Number of rows with at least one hole: 7
通過使用scipy.ndimage.measurements.label計數連續的0組,我能夠做到1
。
In[2]: scipy.ndimage.measurements.label(arr == 0,
structure=[[0,1,0],
[0,0,0],
[0,1,0]])[1] - arr.shape[1]
Out[2]: 12
我將如何找到2
和3
? 我想避免使用循環。
這是使用xor和np.where
一種方法:
# mark all the places where A changes in vertical direction
# pad in such a way that the first change in each column is up and the last down
B = np.empty(np.array([1,0])+A.shape, int)
B[:-1] = A
B[1:-1] ^= A[:-1]
B[-1] = A[-1]
# retrieve coordinates of switch points
x, y = np.where(B.T)
# group in pairs, the differences in y are the hole depths
x = x[::2]
d = np.subtract(*y.reshape(-1, 2).T[::-1])
# exclude holes that were introduced by padding
x, d = x[y[1::2]!=len(A)], d[y[1::2]!=len(A)]
# now we have the column numbers and hole depths
x
# array([1, 2, 2, 3, 5, 6, 6, 7, 7, 8, 8, 9])
d
# array([3, 1, 1, 1, 3, 8, 2, 1, 2, 1, 1, 3])
# the sum of the depths
d.sum()
# 27
# and the rows with holes
unq = np.unique(y[1::2])
# make sure not to count padded holes
unq.size - (unq[-1] == len(A))
# 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.