简体   繁体   中英

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]]) 

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]]

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
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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM