Numpy.选择从3D阵列

2024-03-29 14:19:46 发布

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

假设我有以下numpy数组:

>>a
array([[0, 0, 2],
       [2, 0, 1],
       [2, 2, 1]])
>>b
array([[2, 2, 0],
       [2, 0, 2],
       [1, 1, 2]])

然后垂直堆叠

^{pr2}$

导致:

>>c
array([[[0, 2],
        [0, 2],
        [2, 0]],

       [[2, 2],
        [0, 0],
        [1, 2]],

       [[2, 1],
        [2, 1],
        [1, 2]]])

由此,我希望,对于c的每个3d维,检查这个子数组中存在哪个组合,然后根据列表匹配的索引对其进行编号。我试过下面的方法,但没用。对于双for循环,该算法非常简单,但是由于c非常大,它的速度非常慢。在

classes=[(0,0),(2,1),(2,2)]
out=np.select( [h==c for h in classes], range(len(classes)), default=-1)

我想要的输出是

out = [[-1,-1,-1],
       [3,  1,-1],
       [2,  2,-1]]

Tags: 方法innumpy算法列表fornp数组
3条回答

您可以像这样分别测试a和b阵列:

clsa = (0,2,2)
clesb = (0,1,2)

np.select ( [(ca==a) & (cb==b) for ca,cb in zip (clsa, clsb)], range (3), default = -1)

它将获得所需的结果(除了返回0,1,2而不是1,2,3)。在

这个怎么样:

(np.array([np.array(h)[...,:] == c for h in classes]).all(axis = -1) *
         (2 + np.arange(len(classes)))[:, None, None]).max(axis=0) - 1

它会返回你真正需要的东西

^{pr2}$

这里有另一种方法可以得到你想要的,我会把它贴出来,以防对任何人有用。在

import numpy as np

a = np.array([[0, 0, 2],
              [2, 0, 1],
              [2, 2, 1]])
b = np.array([[2, 2, 0],
              [2, 0, 2],
              [1, 1, 2]])
classes=[(0,0),(2,1),(2,2)]

c = np.empty(a.shape, dtype=[('a', a.dtype), ('b', b.dtype)])
c['a'] = a
c['b'] = b
classes = np.array(classes, dtype=c.dtype)
classes.sort()
out = classes.searchsorted(c)
out = np.where(c == classes[out], out+1, -1)
print out
#array([[-1, -1, -1]
#       [ 3,  1, -1]
#       [ 2,  1, -1]])

相关问题 更多 >