计算numpy 2D矩阵中的“洞”

2024-04-27 18:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

给定1和0的二维矩阵,例如-

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

我怎样才能找到23?我想避免使用循环。你知道吗


Tags: ofnonumberwithscipyonelabelat
1条回答
网友
1楼 · 发布于 2024-04-27 18:11:09

这里有一种使用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

相关问题 更多 >