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 m = np.array([[ 1, 2, 3, 4, 5, 6], [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], [11, 12, 13, 14, 15, 16], [21, 22, 23, 24, 25, 26], [31, 32, 33, 34, 35, 36], [41, 42, 43, 44, 45, 46]]) | 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],-1, 3).swapaxes(0,1) #2 m.reshape(m.shape[0],-1, 2).swapaxes(0,1) #3 m.reshape(m.shape[0],-1, 1).swapaxes(0,1) | cs |
#1 array([[[ 1, 2, 3], [11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]], [[ 4, 5, 6], [14, 15, 16], [24, 25, 26], [34, 35, 36], [44, 45, 46]]]) #2 array([[[ 1, 2], [11, 12], [21, 22], [31, 32], [41, 42]], [[ 3, 4], [13, 14], [23, 24], [33, 34], [43, 44]], [[ 5, 6], [15, 16], [25, 26], [35, 36], [45, 46]]]) #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