我有兴趣在布尔数组中找出'True'补丁的各个大小。例如,在布尔矩阵中:
[[1, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]]
输出结果为:
[[1, 0, 0, 0],
[0, 4, 4, 0],
[0, 4, 0, 0],
[0, 4, 0, 0]]
我知道我可以递归地执行此操作,但我也认为python数组操作在大规模上是昂贵的并且是否有可用的库函数?
答案 0 :(得分:2)
这是一个快速而简单的完整解决方案:
import numpy as np
import scipy.ndimage.measurements as mnts
A = np.array([
[1, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]
])
# labeled is a version of A with labeled clusters:
#
# [[1 0 0 0]
# [0 2 2 0]
# [0 2 0 0]
# [0 2 0 0]]
#
# clusters holds the number of different clusters: 2
labeled, clusters = mnts.label(A)
# sizes is an array of cluster sizes: [0, 1, 4]
sizes = mnts.sum(A, labeled, index=range(clusters + 1))
# mnts.sum always outputs a float array, so we'll convert sizes to int
sizes = sizes.astype(int)
# get an array with the same shape as labeled and the
# appropriate values from sizes by indexing one array
# with the other. See the `numpy` indexing docs for details
labeledBySize = sizes[labeled]
print(labeledBySize)
输出:
[[1 0 0 0]
[0 4 4 0]
[0 4 0 0]
[0 4 0 0]]
上面最棘手的一句是“花哨的”numpy
索引:
labeledBySize = sizes[labeled]
其中一个数组用于索引另一个数组。有关其工作原理的详细信息,请参阅numpy
indexing docs (section "Index arrays")。
我还将上述代码的一个版本编写为单个紧凑函数that you can try out yourself online.它包含一个基于随机数组的测试用例。