0

在 的文档numpy.take,表示a根据indices和进行索引axis,然后将结果可选地存储在out参数中。是否存在执行索引的函数out?使用花哨的索引它会是这样的:

out[:, :, indices, :] = a

在这里,我假设axis=2但在我的情况下,我事先并不知道轴。使用一维布尔掩码而不是索引的解决方案也是可以接受的。

4

2 回答 2

1

您可以像这样使用交换轴:

>>> A = np.arange(24).reshape(2,3,4)
>>> out = np.empty_like(A)
>>> I = [2,0,1]
>>> axis = 1
>>> out.swapaxes(0, axis)[I] = A.swapaxes(0, axis)
>>> out                                                                                                             
array([[[ 4,  5,  6,  7],                                                                                           
        [ 8,  9, 10, 11],                                                                                           
        [ 0,  1,  2,  3]],                                                                                          

       [[16, 17, 18, 19],                                                                                           
        [20, 21, 22, 23],                                                                                           
        [12, 13, 14, 15]]])                                                                                         
于 2018-06-14T08:32:38.527 回答
0

某些numpy函数在指定轴上操作时会构造索引元组。

代码不是特别漂亮,但通用且相当有效。

In [700]: out = np.zeros((2,1,4,5),int)
In [701]: out
Out[701]: 
array([[[[0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0]]],


       [[[0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0]]]])

In [702]: indices = [3,0,1]

创建一个索引元组。为了便于构造,从列表或数组开始,然后tuple在索引时转换为:

In [703]: idx = [slice(None)]*out.ndim
In [704]: idx[2] = indices
In [705]: idx
Out[705]: 
[slice(None, None, None),
 slice(None, None, None),
 [3, 0, 1],
 slice(None, None, None)]
In [706]: out[tuple(idx)] = 10    
In [707]: out
Out[707]: 
array([[[[10, 10, 10, 10, 10],
         [10, 10, 10, 10, 10],
         [ 0,  0,  0,  0,  0],
         [10, 10, 10, 10, 10]]],


       [[[10, 10, 10, 10, 10],
         [10, 10, 10, 10, 10],
         [ 0,  0,  0,  0,  0],
         [10, 10, 10, 10, 10]]]])

它匹配take

In [708]: np.take(out, indices, axis=2)
Out[708]: 
array([[[[10, 10, 10, 10, 10],
         [10, 10, 10, 10, 10],
         [10, 10, 10, 10, 10]]],


       [[[10, 10, 10, 10, 10],
         [10, 10, 10, 10, 10],
         [10, 10, 10, 10, 10]]]])

我们可以设置更复杂的值,只要我们得到正确的广播:

out[tuple(idx)] = np.array([10,11,12])[...,None]

我还看到numpy了将感兴趣的轴移动到已知位置的功能——无论是开始还是结束。根据操作,它可能需要换回。


有像place, put,之类的函数copyto提供了其他控制分配的方法(除了通常的索引)。但是没有一个axis参数像np.take.

于 2018-06-14T15:16:59.720 回答