6

I have a array like following,

from numpy import *
a=array([1,2,3,4,5,6,7,8,9])

I want to get the result like following

[[1,4,7],[2,5,8],[3,6,9]]

Because I have a big array. So i need a efficient way to do it . And it's better to reshape it in-place.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Samuel
  • 5,977
  • 14
  • 55
  • 77
  • if you use fortran-order, do know that nearly everything you do with an array in fortran-order returns a result in C-order (and maybe first even transforms to C-order before doing stuff with it) but it would be interesting to know what you can/want to speed up with it – usethedeathstar Aug 27 '13 at 14:23

2 Answers2

8

You can use reshape passing order='F'. Whenever possible, the returned array will be only a view of the original one, without data being copied, for example:

a = np.arange(1, 10)
# array([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = a.reshape(3, 3)
c = a.reshape(3, 3, order='F')

a[0] = 11

print(b)
#array([[ 11,  4,  7],
#       [ 2,  5,  8],
#       [ 3,  6,  9]])

print(c)
#array([[ 11,  4,  7],
#       [ 2,  5,  8],
#       [ 3,  6,  9]])

The flags property can be used to check the memory order and data ownership of an array:

print(a.flags)
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

print(b.flags)
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

print(c.flags)
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
5

You can use reshape and change the order parameter to FORTRAN (column-major) order:

 a.reshape((3,3),order='F')
Lee
  • 29,398
  • 28
  • 117
  • 170