2

i have a numpy array of shape (12,). I want to reshape it so that [[1,2,3,4,5,6,7,8,9,10,11,12]] becomes

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

I have tried a.reshape(3,4) and a.reshape(-1,4) but nothing is producing what i want. is there a simple way of doing this or do i need to create a new array and set each value individually?

csbk
  • 559
  • 3
  • 9
  • 12

1 Answers1

3

Reshape to split the first axis into two with the latter of length 3 and transpose -

a.reshape(-1,3).T

Or reshape in fortran order with reshaping parameters flipped -

a.reshape(3,-1, order='F')

Sample run -

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

In [715]: a.reshape(-1,3).T
Out[715]: 
array([[ 1,  4,  7, 10],
       [ 2,  5,  8, 11],
       [ 3,  6,  9, 12]])

In [719]: a.reshape(3,-1, order='F')
Out[719]: 
array([[ 1,  4,  7, 10],
       [ 2,  5,  8, 11],
       [ 3,  6,  9, 12]])
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • I wonder if it would be worth adding a note to the numpy docs saying that `.reshape((A, B, C)).T` is the same as `.reshape((C, B, A), order='F)` - seems like a good way to explain the `order` argument – Eric Nov 24 '17 at 17:42
  • @Eric That actually makes sense and sounds simpler. So, sure, worth adding that way into the docs I think. – Divakar Nov 24 '17 at 17:47