Array Manipulation

Array manipulation has some routines for performing the operations on array-like reshaping, transpose. etc. Let’s discuss some usable and important routines. Let’s start.
1. Changing array shape
A.)]Reshape(a, newshape[, order]) ->Gives a new shape to an array without changing its data.
B.)ravel(a[, order]) ->Return a contiguous flattened array.
C.)ndarray.flat ->A 1-D iterator over the array.
D.)ndarray.flatten ->Return a copy of the array collapsed into one dimension.
 
Changing array shape
import numpy as np
a = np.arange(6)
print(a)
[0 1 2 3 4 5]

1. Reshaping

a.reshape(2,3)
array([[0, 1, 2],
       [3, 4, 5]])

2. Flattening the array

a.ravel()
array([0, 1, 2, 3, 4, 5])

3.numpy.ndarray.flat

x = np.arange(1, 7).reshape(2, 3)
x
array([[1, 2, 3],
       [4, 5, 6]])
x.flat[3]
4
print(x.T)
x.T.flat[3]
[[1 4]
 [2 5]
 [3 6]]
5

4.Flatten

a = np.array([[1,2], [3,4]])
a.flatten()
array([1, 2, 3, 4])
 
2. Transpose Operation
A.) Numpy.moveaxis(a, source, destination ) ->Move axes of an array to new positions. It will be more clear to you through examples only. Just go through comments written with the code which will make easy to understand.
B.) Numpy.transpose(a, axes=None) ->Permute the dimensions of an array.By default, it reverses the dimensions, otherwise, permute the axes according to the values given.
C.) Numpy.ndarray.T ->Same as self.transpose(), except that self is returned if self.ndim
 
Transpose routine

1. moveaxis routine

import numpy as np
x = np.zeros((3, 4, 5))
## In this all the elements shape gets shifted in the direction of source to destonation, so for this example 
## it is just like cyclic rotation in clockwise direction.
np.moveaxis(x, 0, -1).shape
(7, 5, 4, 6)
np.moveaxis(x, -1, 0).shape
(5, 3, 4)
## In this example, last axes remain unchanged.
np.moveaxis(x, 0, 1).shape
(7, 6, 5, 4)
x = np.zeros((6, 7, 5, 4))
np.moveaxis(x, 0, 2).shape
(7, 5, 6, 4)

2. numpy.transpose

x = np.arange(4).reshape((2,2))
x
array([[0, 1],
       [2, 3]])
np.transpose(x)
array([[0, 2],
       [1, 3]])
## In this example we doesn't set the axes=none and here we set axes-0 dimensions to axes-1, axes-1 dimensions to axes-0 etc.   
x = np.ones((1, 2, 3))
np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)

3. numpy.ndarray.T

x = np.array([[1.,2.],[3.,4.]])
x
array([[1., 2.],
       [3., 4.]])
 x.T
array([[1., 3.],
       [2., 4.]])
2. Changing number of direction
 
A.) Numpy.atleast_1d ->Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
 

Leave a Comment

Your email address will not be published. Required fields are marked *