Nazmul Ahasan
Nazmul Ahasan

Reputation: 34

Reshape numpy array in z axis

I have a data set like this

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

How can I reshape this into shape (3,2,2) so that a[:,0,0] = [1,2,3]?

Upvotes: 0

Views: 1016

Answers (2)

hpaulj
hpaulj

Reputation: 231615

In [30]: a=np.arange(1,13)
In [31]: a
Out[31]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

Since you want to keep the first 3 values 'together', we could start with a reshape like:

In [32]: a.reshape(2,2,3)
Out[32]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

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

and then swap a couple of the axes:

In [33]: a.reshape(2,2,3).transpose(2,0,1)
Out[33]: 
array([[[ 1,  4],
        [ 7, 10]],

       [[ 2,  5],
        [ 8, 11]],

       [[ 3,  6],
        [ 9, 12]]])
In [34]: _[:,0,0]
Out[34]: array([1, 2, 3])

Or with a different transpose:

In [35]: a.reshape(2,2,3).transpose(2,1,0)
Out[35]: 
array([[[ 1,  7],
        [ 4, 10]],

       [[ 2,  8],
        [ 5, 11]],

       [[ 3,  9],
        [ 6, 12]]])

transpose() with an argument, (also invoked with .T) does the same thing.

So your question is a bit ambiguous.

So does the reshape with order F mentioned in the other answer:

In [37]: a.reshape(3,2,2, order='F')
Out[37]: 
array([[[ 1,  7],
        [ 4, 10]],

       [[ 2,  8],
        [ 5, 11]],

       [[ 3,  9],
        [ 6, 12]]])

(though the two step, a.reshape(3,4, order='F').reshape(3,2,2) produces my first result Out[33]).

Upvotes: 1

one
one

Reputation: 2585

you can use two steps: step1.

In [28]: b1 = np.reshape(a,(3,4), order='F')

In [29]: b1
Out[29]:
array([[ 1,  4,  7, 10],
       [ 2,  5,  8, 11],
       [ 3,  6,  9, 12]])

use order='F' means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. numpy.reshape

setp2

In [30]: c = b1.reshape(3,2,2)

In [31]: c
Out[31]:
array([[[ 1,  4],
        [ 7, 10]],

       [[ 2,  5],
        [ 8, 11]],

       [[ 3,  6],
        [ 9, 12]]])

get the final result:

In [34]: c[:,0,0]
Out[34]: array([1, 2, 3])

Upvotes: 1

Related Questions