Python : split a 2d array vertically and convert it into a 3d array

This post shows how to split a 2d array into subsets of 2d arrays and convert them into a 3d array.


Slice a 2d array vertically and convert it into a 3d array



The following figure shows what we want to do in this post.

Exercise with code snippets


For example, let' consider m which is a 2d array.

# slice vertically 2d array and convert them to 3d array
 
import numpy as np
 
= np.array([[ 123456],
              [11,12,13,14,15,16],
              [21,22,23,24,25,26],
              [31,32,33,34,35,36],
              [41,42,43,44,45,46]])
m
 
cs

array([[ 1,  2,  3,  4,  5,  6],
       [111213141516],
       [212223242526],
       [313233343536],
       [414243444546]])
 
 
cs

The following code examples split m (2d array) vertically into 2, 3, or 6 sub 2d arrays and concatenate them as a 3d array. The third argument of reshape() function is the number of sub columns. swapaxes(0,1) swaps .shape[0] and .shape[1].

The only thing we do is just to select the number of sub columns.

# slice vertically 2d array and convert them to 3d array
 
#1
m.reshape(m.shape[0],-13).swapaxes(0,1)
#2
m.reshape(m.shape[0],-12).swapaxes(0,1)
#3
m.reshape(m.shape[0],-11).swapaxes(0,1)
 
 
cs

#1
array([[[ 1,  2,  3],
        [111213],
        [212223],
        [313233],
        [414243]],
       [[ 4,  5,  6],
        [141516],
        [242526],
        [343536],
        [444546]]])
#2
array([[[ 1,  2],
        [1112],
        [2122],
        [3132],
        [4142]],
       [[ 3,  4],
        [1314],
        [2324],
        [3334],
        [4344]],
       [[ 5,  6],
        [1516],
        [2526],
        [3536],
        [4546]]])
#3
array([[[ 1],
        [11],
        [21],
        [31],
        [41]],
 
       [[ 2],
        [12],
        [22],
        [32],
        [42]],
 
       [[ 3],
        [13],
        [23],
        [33],
        [43]],
 
       [[ 4],
        [14],
        [24],
        [34],
        [44]],
 
       [[ 5],
        [15],
        [25],
        [35],
        [45]],
 
       [[ 6],
        [16],
        [26],
        [36],
        [46]]])
 
cs

No comments:

Post a Comment