Python Numpy module provides a series functions that can reshape Numpy arrays. When an array is created via Numpy, it has a shape and dimension. reshape() is used to rearrange all elements of the array with another specified shape. Comparatively, ravel() will reshape the object to an one-dimensional array, If the original array has shape (x1,x2), transpose() will transform its shape to (x2,x1). Next, we will show several examples of array shape manipulation in Python.
#Import Numpy module
import numpy as np
#create an one-dimensional array of 20 elements
B = np.random.random(20)
B
#output
array([0.87049167, 0.98208694, 0.76247996, 0.53349063, 0.10419605,
0.75908853, 0.20081232, 0.93892132, 0.74249042, 0.22420541,
0.18680545, 0.79214439, 0.12376144, 0.76080517, 0.33618041,
0.60158737, 0.5252644 , 0.61641478, 0.40580038, 0.30622666])
#reshape array into shape (5,4) and store to a new array
B2 = B.reshape(5,4)
B2
#output
array([[0.87049167, 0.98208694, 0.76247996, 0.53349063],
[0.10419605, 0.75908853, 0.20081232, 0.93892132],
[0.74249042, 0.22420541, 0.18680545, 0.79214439],
[0.12376144, 0.76080517, 0.33618041, 0.60158737],
[0.5252644 , 0.61641478, 0.40580038, 0.30622666]])
#reshape array again to shape (4,5)
B2.shape = (4, 5)
B2
#output
array([[0.87049167, 0.98208694, 0.76247996, 0.53349063, 0.10419605],
[0.75908853, 0.20081232, 0.93892132, 0.74249042, 0.22420541],
[0.18680545, 0.79214439, 0.12376144, 0.76080517, 0.33618041],
[0.60158737, 0.5252644 , 0.61641478, 0.40580038, 0.30622666]])
#using ravel() to reshape array into one-dimension, and store to a new object
B1 = B2.ravel()
B1
#output
array([0.87049167, 0.98208694, 0.76247996, 0.53349063, 0.10419605,
0.75908853, 0.20081232, 0.93892132, 0.74249042, 0.22420541,
0.18680545, 0.79214439, 0.12376144, 0.76080517, 0.33618041,
0.60158737, 0.5252644 , 0.61641478, 0.40580038, 0.30622666])
# using transpose() to reshape original array to shape
#row and column is original column and row
B2.transpose()
array([[0.87049167, 0.98208694, 0.76247996, 0.53349063],
[0.10419605, 0.75908853, 0.20081232, 0.93892132],
[0.74249042, 0.22420541, 0.18680545, 0.79214439],
[0.12376144, 0.76080517, 0.33618041, 0.60158737],
[0.5252644 , 0.61641478, 0.40580038, 0.30622666]])
0 Comments