我很想了解布尔数组中“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数组操作是代价高昂的,是否有可用的库函数可以完成此任务?
我很想了解布尔数组中“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数组操作是代价高昂的,是否有可用的库函数可以完成此任务?
这里有一个快速简单的完整解决方案:
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
索引文档(“索引数组”部分)。
我还编写了上述代码的单个紧凑函数版本,您可以在线尝试。它包括基于随机数组的测试用例。
numpy
高级索引操作。此外,还提供了一个在线测试案例的链接,基于随机数组。 - tel
scipy.ndimage.measurements
中有你需要的内容。 - tel