3

我有一个 3d 数组

A = np.random.random((4,4,3))

和一个索引矩阵

B = np.int_(np.random.random((4,4))*3)

如何根据索引矩阵 B 从 A 获取二维数组?

一般来说,如何从一个 ND 数组和一个 N-1 维索引数组中得到一个 N-1 维数组?

4

1 回答 1

3

举个例子:

>>> A = np.random.randint(0,10,(3,3,2))
>>> A
array([[[0, 1],
        [8, 2],
        [6, 4]],

       [[1, 0],
        [6, 9],
        [7, 7]],

       [[1, 2],
        [2, 2],
        [9, 7]]])

使用花哨的索引来获取简单的索引。请注意,所有索引必须具有相同的形状,并且每个索引的形状将是返回的内容。

>>> ind = np.arange(2)
>>> A[ind,ind,ind]
array([0, 9]) #Index (0,0,0) and (1,1,1)

>>> ind = np.arange(2).reshape(2,1)
>>> A[ind,ind,ind]
array([[0],
       [9]])

因此,对于您的示例,我们需要为前两个维度提供网格:

>>> A = np.random.random((4,4,3))
>>> B = np.int_(np.random.random((4,4))*3)
>>> A
array([[[ 0.95158697,  0.37643036,  0.29175815],
        [ 0.84093397,  0.53453123,  0.64183715],
        [ 0.31189496,  0.06281937,  0.10008886],
        [ 0.79784114,  0.26428462,  0.87899921]],

       [[ 0.04498205,  0.63823379,  0.48130828],
        [ 0.93302194,  0.91964805,  0.05975115],
        [ 0.55686047,  0.02692168,  0.31065731],
        [ 0.92822499,  0.74771321,  0.03055592]],

       [[ 0.24849139,  0.42819062,  0.14640117],
        [ 0.92420031,  0.87483486,  0.51313695],
        [ 0.68414428,  0.86867423,  0.96176415],
        [ 0.98072548,  0.16939697,  0.19117458]],

       [[ 0.71009607,  0.23057644,  0.80725518],
        [ 0.01932983,  0.36680718,  0.46692839],
        [ 0.51729835,  0.16073775,  0.77768313],
        [ 0.8591955 ,  0.81561797,  0.90633695]]])
>>> B
array([[1, 2, 0, 0],
       [1, 2, 0, 1],
       [2, 1, 1, 1],
       [1, 2, 1, 2]])

>>> x,y = np.meshgrid(np.arange(A.shape[0]),np.arange(A.shape[1]))
>>> x
array([[0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3]])
>>> y
array([[0, 0, 0, 0],
       [1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3]])

>>> A[x,y,B]
array([[ 0.37643036,  0.48130828,  0.24849139,  0.71009607],
       [ 0.53453123,  0.05975115,  0.92420031,  0.36680718],
       [ 0.10008886,  0.02692168,  0.86867423,  0.16073775],
       [ 0.26428462,  0.03055592,  0.16939697,  0.90633695]])
于 2013-09-09T17:04:45.517 回答