Python Attribute Arrays

Numpy's array class is called ndarray . It is also known by alias name array . Let's remember that there is another class 'array' in Python that is different from numpy's 'array' class. This class contains the following important attributes (or variables):

The ndim Attribute

The 'ndim ' attribute represents the number of dimensions or axes of the array. The number of dimensions is also referred to as 'rank '. For a single dimensional array, it is 1 and for a two dimensional array, it is 2. Consider the following code snippet:

CopiedCopy Code

arr1 = array([1,2,3,4,5]) 
print(arr1.ndim)
arr2 = array([[1,2,3], [4,5,6]]) 
print(arr2.ndim)

The shape Attribute

The 'shape' attribute gives the shape of an array. The shape is a tuple listing the number of elements along each dimension. A dimension is called an axis. For a 1D array, shape gives the number of elements in the row. For a 2D array, it specifies the number of rows and columns in each row. We can also change the shape using 'shape' attribute.

CopiedCopy Code

arr1 = array([1,2,3,4,5]) 
print(arr1.shape)
arr2 = array([[1,2,3], [4,5,6]]) 
print(arr2.shape)
arr3 = array([[[1,2,3],[4,5,6]], 
                       [[1,1,1], [1,0,1]]])
print(arr3.shape)

The size Attribute

The 'size' attribute gives the total number of elements in the array. For example, consider the following code snippet:

CopiedCopy Code

arr1 = array([1,2,3,4,5]) 
print(arr1.size)
arr2 = array([[1,2,3], [4,5,6]]) 
print(arr2.size)

The itemsize Attribute

Attribute The 'itemsize' attribute gives the memory size of the array element in bytes. As we know, 1 byte is equal to 8 bits. For example consider the following code snippet:

CopiedCopy Code

arr1 = array([1,2,3,4,5]) 
print(arr1.itemsize)
arr2 = array([1.1,2.1,3.5,4,5.0]) 
print(arr2.itemsize)							
							

The nbytes Attribute

The 'nbytes ' attribute gives the total number of bytes occupied by an array. The total number of bytes = size of the array * item size of each element in the array. For example,

arr2 = array([[1,2,3], [4,5,6]]) print(arr2.nbytes)

Apart from the attributes discussed in the preceding sections, we can use reshape() and flatten() methods which are useful to convert the 1D array into a 2D array and vice versa.

The reshape() arrays method

The 'reshape() ' method is useful to change the shape of an array. The new array should have the same number of elements as in the original array. For example,

CopiedCopy Code

arr1 = arange(10)
print(arr1)
arr1 = arr1.reshape(2, 5) 
print(arr1)
arr1 = arr1.reshape(5, 2) 
print(arr1)

The flatten() arrays method

The flatten() method is useful to return a copy of the array collapsed into one dimension. For example, let's take a 2D array as:

CopiedCopy Code

arr1 = array([[1,2,3],[4,5,6]]) 
print(arr1)
arr1 = arr1.flatten() 
print(arr1)