Reshaping a Julia-stored array in Python

Viewed 147

I'm struggling with this issue since a while now, so I decided to ask you for some help. So, for short, my problem is the following...

All of my codes are in Julia, and the data processed by them has been stored as Julia does(I guess in column-major oder), but now I need to run some code in python that reads some of these data and reshape it. But, as the data is stored and read differently in both lenguajes, reshaping is not behaving as I would excpect (not that it is wrong, just not what I wanted) As an example... In Julia, when I reshape an 1D-array into a (2,3,4)-array dimention, I get:

julia> a=collect(1:24);
julia> r=reshape(a,2,3,4)
2×3×4 Array{Int64,3}:
[:, :, 1] =
1  3  5
2  4  6

[:, :, 2] =
7   9  11
8  10  12

[:, :, 3] =
13  15  17
14  16  18

[:, :, 4] =
19  21  23
20  22  24

While in python I get,

b=np.arange(1,25);
r=b.reshape(4,2,3)

gives

In [200]: r
array([[[ 1,  2,  3],
    [ 4,  5,  6]],

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

   [[13, 14, 15],
    [16, 17, 18]],

   [[19, 20, 21],
    [22, 23, 24]]])

Is there any way to achieve in Python the same result of that obtained in the Julia example?..

1 Answers

You can write:

>>> np.transpose(b.reshape(4,3,2), (2,1,0))
array([[[ 1,  7, 13, 19],
        [ 3,  9, 15, 21],
        [ 5, 11, 17, 23]],

       [[ 2,  8, 14, 20],
        [ 4, 10, 16, 22],
        [ 6, 12, 18, 24]]])

EDIT:

As explained in https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.transpose.html the second argument of np.transpose permutes axes of an array according to the values given as a second argument. Actually in this case you could just write np.transpose(b.reshape(4,3,2)) as by default np.transpose reverses the dimensions which is needed here.

Related