Home > Mobile >  transfer 3D numpy array into a 2D numpy array
transfer 3D numpy array into a 2D numpy array

Time:11-19

Idk how to describe my problem. I guess it's not a tricky one, but I don't know how to describe it or how to solve this. let's say a NumPy array

a = np.array(
    [[[1,2,3],
      [4,5,6]]

     [[7,8,9],
      [10,11,12]]])

the shape will be like (2,2,3). I'd like to make it look like this:

a = np.array(
[[1,2,3],
 [7,8,9],
 [4,5,6],
 [10,11,12]]
)

which shape will be like (4,3). if I use reshape, it will look like this: which is NOT what I want.

a = np.array(
[[1,2,3],
 [4,5,6],
 [7,8,9], 
 [10,11,12]]
)

how to do this? And how to call this process? please.

CodePudding user response:

One way using numpy.stack and vstack:

np.vstack(np.stack(a, 1))

Output:

array([[ 1,  2,  3],
       [ 7,  8,  9],
       [ 4,  5,  6],
       [10, 11, 12]])

CodePudding user response:

By using indexing method, an idx list could be created that specifies which indices of the ex a must be placed as which indices in the new one i.e. idx is a rearranging list:

idx = [0, 2, 1, 3]
a = a.reshape(4, 3)[idx]

a is firstly reshaped to the intended shape, which is (4,3), and then rearranged by the idx. idx[1] = 2 is showing that value in index = 2 of the ex a will be replaced to index = 1 in the new a.

CodePudding user response:

Here is a more pythonic version of your problem. This uses concatenate so append the rows of your array.

a = np.array(
    [[[1,2,3],
      [4,5,6]],
     [[7,8,9],
      [10,11,12]]]
)

def transform_2d(a_arr):
    nrow = len(a[:])
    all = a_arr[:,0]
    for i in range(1,nrow):
        all = np.concatenate((all, a_arr[:,i] ))
    return all

print(transform_2d(a))

CodePudding user response:

First use transpose (or swapaxes) to bring the desire rows together:

In [268]: a.transpose(1,0,2)
Out[268]: 
array([[[ 1,  2,  3],
        [ 7,  8,  9]],

       [[ 4,  5,  6],
        [10, 11, 12]]])

then the reshape follows:

In [269]: a.transpose(1,0,2).reshape(-1,3)
Out[269]: 
array([[ 1,  2,  3],
       [ 7,  8,  9],
       [ 4,  5,  6],
       [10, 11, 12]])
  • Related