网格中的每个位置都与一个由和中的一个值组成的元组相关
asp
联。例如,左上角有 tuple 。我们想将此元组映射到唯一标识此元组的数字。slp
elv
(8,9,13)
一种方法是将其(8,9,13)
视为 3D 数组的索引
np.arange(9*13*17).reshape(9,13,17)
。选择此特定数组以容纳和中asp
的最大值:slp
elv
In [107]: asp.max()+1
Out[107]: 9
In [108]: slp.max()+1
Out[108]: 13
In [110]: elv.max()+1
Out[110]: 17
现在我们可以将元组 (8,9,13) 映射到数字 1934:
In [113]: x = np.arange(9*13*17).reshape(9,13,17)
In [114]: x[8,9,13]
Out[114]: 1934
如果我们对网格中的每个位置执行此操作,那么我们会为每个位置获得一个唯一编号。我们可以在这里结束,让这些唯一的数字作为标签。
np.unique
或者,我们可以使用with
return_inverse=True
生成更小的整数标签(从 0 开始并增加 1):
uniqs, labels = np.unique(vals, return_inverse=True)
labels = labels.reshape(vals.shape)
所以,例如,
import numpy as np
asp = np.array([8,1,1,2,7,8,2,3,7,6,4,3,6,5,5,4]).reshape((4,4)) #aspect
slp = np.array([9,10,10,9,9,12,12,9,10,11,11,9,9,9,9,9]).reshape((4,4)) #slope
elv = np.array([13,14,14,13,14,15,16,14,14,15,16,14,13,14,14,13]).reshape((4,4)) #elevation
x = np.arange(9*13*17).reshape(9,13,17)
vals = x[asp, slp, elv]
uniqs, labels = np.unique(vals, return_inverse=True)
labels = labels.reshape(vals.shape)
产量
array([[11, 0, 0, 1],
[ 9, 12, 2, 3],
[10, 8, 5, 3],
[ 7, 6, 6, 4]])
只要asp
,slp
和中的值elv
是小整数,上述方法就可以正常工作。如果整数太大,它们的最大值的乘积可能会溢出可以传递给的最大允许值np.arange
。此外,生成如此大的数组效率低下。如果这些值是浮点数,那么它们不能被解释为 3D 数组的索引x
。
因此,要解决这些问题,请先将,中np.unique
的值转换为唯一的整数标签:asp
slp
elv
indices = [ np.unique(arr, return_inverse=True)[1].reshape(arr.shape) for arr in [asp, slp, elv] ]
M = np.array([item.max()+1 for item in indices])
x = np.arange(M.prod()).reshape(M)
vals = x[indices]
uniqs, labels = np.unique(vals, return_inverse=True)
labels = labels.reshape(vals.shape)
这会产生与上面所示相同的结果,但即使asp
, slp
,elv
是浮点数和/或大整数也有效。
最后,我们可以避免生成np.arange
:
x = np.arange(M.prod()).reshape(M)
vals = x[indices]
通过计算vals
指数和步幅的乘积:
M = np.r_[1, M[:-1]]
strides = M.cumprod()
indices = np.stack(indices, axis=-1)
vals = (indices * strides).sum(axis=-1)
所以把它们放在一起:
import numpy as np
asp = np.array([8,1,1,2,7,8,2,3,7,6,4,3,6,5,5,4]).reshape((4,4)) #aspect
slp = np.array([9,10,10,9,9,12,12,9,10,11,11,9,9,9,9,9]).reshape((4,4)) #slope
elv = np.array([13,14,14,13,14,15,16,14,14,15,16,14,13,14,14,13]).reshape((4,4)) #elevation
def find_labels(*arrs):
indices = [np.unique(arr, return_inverse=True)[1] for arr in arrs]
M = np.array([item.max()+1 for item in indices])
M = np.r_[1, M[:-1]]
strides = M.cumprod()
indices = np.stack(indices, axis=-1)
vals = (indices * strides).sum(axis=-1)
uniqs, labels = np.unique(vals, return_inverse=True)
labels = labels.reshape(arrs[0].shape)
return labels
print(find_labels(asp, slp, elv))
# [[ 3 7 7 0]
# [ 6 10 12 4]
# [ 8 9 11 4]
# [ 2 5 5 1]]