ARRAY ATTRIBUTES IN NUMPY
In this tutorial, we are going to learn about different array attributes in Numpy that are essential to know if you want to transform your arrays.
Array Attributes in Numpy
Array attributes are essential to find out the shape, dimension, item size etc. If connected with the ndarray object of numpy then we can find about these in detail. Let us look at some of these attributes with their respective examples as well.
ndarray.shape
By using this method in numpy you can know the array dimensions. It can also be used to resize the array.
import numpy as np arr = np.array([[1,2,3,4],[5,6,7,8]]) arr
Output:
array([[1, 2, 3, 4], [5, 6, 7, 8]])
You can change the shape of the array by rearranging the tuple.
arr.shape = (4,2) arr
Output:
array([[1, 2], [3, 4], [5, 6], [7, 8]])
ndarray.ndim
This method returns the number of dimensions of an array.
arr = n.array([[1,2,3,4],[5,6,7,8]]) arr
Output:
array([[1, 2, 3, 4], [5, 6, 7, 8]])
arr = np.arange(10).reshape(2,5) arr
Output:
array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
arr.ndim
Output:
2
ndarray.itemsize
This method returns the length of the array of each component in bytes.
import numpy as np arr = np.array([1,2,3,4,5]) arr.itemsize
Output:
8
ndarray.T
This method creates the transpose method for the array i.e. converts rows into columns and columns into rows:
arr = np.array([[1,2,3,4],[5,6,7,8]]) arr
Output:
array([[1, 2, 3, 4],[5, 6, 7, 8]])
Applying the transpose method
arr.T
Output:
array([[1, 5], [2, 6], [3, 7], [4, 8]])
References: Scipy Docs