Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.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
通过选择减少numpy数组的维数_Numpy - Fatal编程技术网

通过选择减少numpy数组的维数

通过选择减少numpy数组的维数,numpy,Numpy,我有一个3d阵列 A = np.random.random((4,4,3)) 和一个索引矩阵 B = np.int_(np.random.random((4,4))*3) 如何基于索引矩阵B从a获取2D数组 一般来说,如何从ND数组和N-1维索引数组中获取N-1维数组?让我们举一个例子: >>> A = np.random.randint(0,10,(3,3,2)) >>> A array([[[0, 1], [8, 2],

我有一个3d阵列

A = np.random.random((4,4,3))
和一个索引矩阵

B = np.int_(np.random.random((4,4))*3)
如何基于索引矩阵B从a获取2D数组

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

让我们举一个例子:

>>> 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]])

你能再解释一下吗。。。数组
B
应该如何索引?您希望使用哪些维度来切片
A
?e、 g.
B[0,0]==2表示什么?为了简化,我只想沿轴选择一个项目。对于4x3阵列,有4x4这样的选择。所以索引数组是一个4x4矩阵。