Alex Witsil
Alex Witsil

Reputation: 862

Python reshaping 1D array into 2D array by 'rows' or 'columns'

I would like to control how array.reshape() populates the new array. For example

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

but what I would like to be able to is populate the array columnwise with something like:

a = np.arange(9).reshape(3,3, 'columnwise')
## array([[ 0,  3,  6,  9],
##   [ 1,  4,  7,  10],
##   [ 2,  5, 8, 11]]) 

Upvotes: 1

Views: 500

Answers (3)

Son Kun
Son Kun

Reputation: 1

If you take a transpose of the original matrix, you will get your desired effect.

import numpy as np
a = np.arange(6).reshape(3,3).tranpose()

OR

a = np.arange(6).reshape(3,3).T

Upvotes: 0

hpaulj
hpaulj

Reputation: 231738

In [22]:  np.arange(12).reshape(3,4, order='F')                                                        
Out[22]: 
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10],
       [ 2,  5,  8, 11]])

Upvotes: 0

dildeolupbiten
dildeolupbiten

Reputation: 1342

Use np.transpose.

import numpy as np

print(np.arange(9).reshape(3,3).transpose())

Output:

[[0 3 6]
 [1 4 7]
 [2 5 8]]

Upvotes: 2

Related Questions