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:



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.


The size Attribute

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


The itemsize

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:


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() 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,



The flatten() 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: