Numpy array attributes with examples

Spread the love

There are various attributes of numpy array, let’s look at them one by one.

1 . Shape –

The shape attribute returns a tuple containing the length of each dimension of the array.

In [1]: import numpy as np

In [2]: # one dimensional array

In [3]: arr1 = np.array([5, 2, 10, 6])

In [4]: arr1
Out[4]: array([ 5,  2, 10,  6])

In [5]: arr1.shape
Out[5]: (4,)

In [6]: # two dimensional array

In [7]: arr2 = np.ones((2, 3))

In [8]: arr2
Out[8]: 
array([[1., 1., 1.],
       [1., 1., 1.]])

In [9]: arr2.shape
Out[9]: (2, 3)

2. Size –

The size attribute tells you the total number of elements in a numpy array.

In [10]: arr1
Out[10]: array([ 5,  2, 10,  6])

In [11]: arr1.size
Out[11]: 4

In [12]: arr2
Out[12]: 
array([[1., 1., 1.],
       [1., 1., 1.]])

In [13]: arr2.size
Out[13]: 6

3. Ndim –

The ndim attribute tells you the number of dimensions a numpy array has.

In [14]: arr1.ndim
Out[14]: 1

In [15]: arr2.ndim
Out[15]: 2

4. nbytes –

This tells you the number of bytes that is used to store a numpy array.

In [16]: arr1.nbytes
Out[16]: 16

In [17]: arr2.nbytes
Out[17]: 48

5 . dtype –

This attribute tells you the data type of a numpy array.

In [18]: arr1.dtype
Out[18]: dtype('int32')

In [19]: arr2.dtype
Out[19]: dtype('float64')

Related Posts –

  1. How to create a Numpy array in Python
  2. Numpy array data types with examples

Rating: 1 out of 5.

Leave a Reply