NumPy – Array Manipulation:
We can change the array shape using the Array manipulation routines like reshape and ravel.
reshape: This will give us the new shape for an array without changing its data
ravel: This will return the contiguous flattened array.
We can transpose an array using the ndarray.T Operation which will be same if self.ndim is less than 2
Let us work on an example.
Example:
# creating array of 2 * 3 dimension
>>> a=np.array([[1,2,3],[4,5,6]]) >>> a array([[1, 2, 3], [4, 5, 6]])
# using ravel to flatten the array
>>> a.ravel() array([1, 2, 3, 4, 5, 6])
# transpose the array from 2 * 3 dimension to 3 * 2 dimension
>>> a.T array([[1, 4], [2, 5], [3, 6]])
# ravel the transposed array
>>> a.T.ravel() array([1, 4, 2, 5, 3, 6])
# Using the reshape option to revert from ravel.
>>> a.T.ravel().reshape((2,3)) array([[1, 4, 2], [5, 3, 6]])
Using the shape and reshape
>>> a=np.arange(4*3*2) >>> a array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) >>> a.reshape(4,3,2) array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]], [[18, 19], [20, 21], [22, 23]]]) >>> a.shape (24,) >>> b=a.reshape(4,3,2) >>> b array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]], [[18, 19], [20, 21], [22, 23]]]) >>> b.shape (4, 3, 2)