相关疑难解决方法(0)

在NumPy中将4D阵列重塑为2D阵列的直觉和想法

虽然Kronecker-product出于教学原因(没有使用明显的和容易获得的np.kron()),我获得了一个4维数组作为中间结果,我将重塑以获得最终结果.

但是,我仍然无法围绕重塑这些高维阵列.我有这个4D数组:

array([[[[ 0,  0],
         [ 0,  0]],

        [[ 5, 10],
         [15, 20]]],


       [[[ 6, 12],
         [18, 24]],

        [[ 7, 14],
         [21, 28]]]])
Run Code Online (Sandbox Code Playgroud)

这是形状(2, 2, 2, 2),我想重塑它(4,4).有人可能会认为这很明显

np.reshape(my4darr, (4,4))
Run Code Online (Sandbox Code Playgroud)

但是,上述重塑并没有给我预期的结果,即:

array([[ 0,  5,  0, 10],
       [ 6,  7, 12, 14],
       [ 0, 15,  0, 20],
       [18, 21, 24, 28]])
Run Code Online (Sandbox Code Playgroud)

如您所见,预期结果中的所有元素都存在于4D数组中.我根本不能正确地根据需要进行重塑.除了答案之外,如何reshape为这种高维数组做一些解释将是非常有帮助的.谢谢!

python arrays numpy multidimensional-array reshape

17
推荐指数
2
解决办法
3684
查看次数

通过没有循环的2D索引数组索引2D numpy数组

我要寻找一个量化的方式来索引numpy.arraynumpy.array索引.

例如:

import numpy as np

a = np.array([[0,3,4],
              [5,6,0],
              [0,1,9]])

inds = np.array([[0,1],
                 [1,2],
                 [0,2]])
Run Code Online (Sandbox Code Playgroud)

我想构建一个新数组,使得该数组中的每一行(i)都是数组的行(i)a,由数组inds(i)的行索引.我想要的输出是:

array([[ 0.,  3.],   # a[0][:,[0,1]]
       [ 6.,  0.],   # a[1][:,[1,2]] 
       [ 0.,  9.]])  # a[2][:,[0,2]]
Run Code Online (Sandbox Code Playgroud)

我可以用循环实现这个目的:

def loop_way(my_array, my_indices):
    new_array = np.empty(my_indices.shape)
    for i in xrange(len(my_indices)):
        new_array[i, :] = my_array[i][:, my_indices[i]]
    return new_array 
Run Code Online (Sandbox Code Playgroud)

但我正在寻找一种纯粹的矢量化解决方案.

python arrays numpy

10
推荐指数
2
解决办法
2053
查看次数

标签 统计

arrays ×2

numpy ×2

python ×2

multidimensional-array ×1

reshape ×1