python - Convert 3d Numpy array to 2d -


i have 3d numpy array of following form:

array([[[ 1.,  5.,  4.],     [ 1.,  5.,  4.],     [ 1.,  2.,  4.]],     [[ 3.,  6.,  4.],     [ 6.,  6.,  4.],     [ 6.,  6.,  4.]]]) 

is there efficient way convert 2d array of form:

array([[1, 1, 1, 5, 5, 2, 4, 4, 4],    [3, 6, 6, 6, 6, 6, 4, 4, 4]]) 

thanks lot!

in [54]: arr = np.array([[[ 1.,  5.,  4.],                          [ 1.,  5.,  4.],                          [ 1.,  2.,  4.]],                          [[ 3.,  6.,  4.],                          [ 6.,  6.,  4.],                          [ 6.,  6.,  4.]]])  in [61]: arr.reshape((arr.shape[0], -1), order='f') out[61]:  array([[ 1.,  1.,  1.,  5.,  5.,  2.,  4.,  4.,  4.],        [ 3.,  6.,  6.,  6.,  6.,  6.,  4.,  4.,  4.]]) 

the array arr has shape (2, 3, 3). wish keep first axis of length 2, , flatten 2 axes of length 3.

if call arr.reshape(h, w) numpy attempt reshape arr shape (h, w). if call arr.reshape(h, -1) numpy replace -1 whatever integer needed reshape make sense -- in case, arr.size/h.

hence,

in [63]: arr.reshape((arr.shape[0], -1)) out[63]:  array([[ 1.,  5.,  4.,  1.,  5.,  4.,  1.,  2.,  4.],        [ 3.,  6.,  4.,  6.,  6.,  4.,  6.,  6.,  4.]]) 

this want, notice values in each subarray, such as

[[ 1.,  5.,  4.], [ 1.,  5.,  4.], [ 1.,  2.,  4.]] 

are being traversed marching left right before going down next row. want march down rows before going on next column. achieve that, use order='f'.

usually elements in numpy array visited in c-order -- last index moves fastest. if visit elements in f-order first index moves fastest. since in 2d array of shape (h, w), first axis associated rows , last axis columns, traversing array in f-order marches down each row before moving on next column.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -