gpt4 book ai didi

python - 在 numpy 2D 矩阵中计算 "holes"

转载 作者:太空宇宙 更新时间:2023-11-03 21:05:51 25 4
gpt4 key购买 nike

给定一个由 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?我想避免使用循环。

最佳答案

这是使用 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

关于python - 在 numpy 2D 矩阵中计算 "holes",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55410383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com