Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Numpy-索引多维数组的一维_Arrays_Python 3.x_Numpy_Indexing - Fatal编程技术网

Arrays Numpy-索引多维数组的一维

Arrays Numpy-索引多维数组的一维,arrays,python-3.x,numpy,indexing,Arrays,Python 3.x,Numpy,Indexing,我有一个这样的numpy数组,形状(6,2,4): 我有如下选择数组: choices = np.array([[1, 1, 1, 1], [0, 1, 1, 0], [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 1, 1], [0, 0, 0, 1]]) 如何使用choi

我有一个这样的numpy数组,形状
(6,2,4)

我有如下
选择
数组:

choices = np.array([[1, 1, 1, 1],
                    [0, 1, 1, 0],
                    [1, 1, 1, 1],
                    [1, 0, 0, 0],
                    [1, 0, 1, 1],
                    [0, 0, 0, 1]])
如何使用
choices
array仅索引大小为2的中间维度,并以最有效的方式获得形状为
(6,4)
的新numpy数组

结果是:

[[1 3 1 1]
 [3 3 2 3]
 [3 2 3 3]
 [1 3 2 0]
 [1 0 1 1]
 [1 3 1 3]]

我试着通过
x[:,choices,:]
来实现它,但这并没有返回我想要的。我还试着做了
x.take(选项,轴=1)
,但运气不好。

使用
np。沿第二轴take\u
索引-

In [16]: np.take_along_axis(x,choices[:,None],axis=1)[:,0]
Out[16]: 
array([[1, 3, 1, 1],
       [3, 3, 2, 3],
       [3, 2, 3, 3],
       [1, 3, 2, 0],
       [1, 0, 1, 1],
       [1, 3, 1, 3]])
或使用显式
整数数组
索引-

In [22]: m,n = choices.shape

In [23]: x[np.arange(m)[:,None],choices,np.arange(n)]
Out[23]: 
array([[1, 3, 1, 1],
       [3, 3, 2, 3],
       [3, 2, 3, 3],
       [1, 3, 2, 0],
       [1, 0, 1, 1],
       [1, 3, 1, 3]])
In [22]: m,n = choices.shape

In [23]: x[np.arange(m)[:,None],choices,np.arange(n)]
Out[23]: 
array([[1, 3, 1, 1],
       [3, 3, 2, 3],
       [3, 2, 3, 3],
       [1, 3, 2, 0],
       [1, 0, 1, 1],
       [1, 3, 1, 3]])