Numpy array Data Types with examples

Spread the love

Various data types that is supported in Numpy are listed below in the table.

To create a numpy array with various data types, we can use the dtype attribute.


In [1]: import numpy as np

In [2]: # create integer type

In [3]: np.array([5, 10, 15], dtype=np.int)
Out[3]: array([ 5, 10, 15])

In [4]: # create float type

In [5]: np.array([5, 10, 15], dtype=np.float)
Out[5]: array([ 5., 10., 15.])

In [6]: np.array([5, 10, 15], dtype=np.complex)
Out[6]: array([ 5.+0.j, 10.+0.j, 15.+0.j])

It is not necessary to specify the bit size of the data type of the array. Once a numpy array is created you can not change the data type of it, however you can create a new copy of it using typecasting to change the data type.

In [7]: arr1 = np.array([5, 10, 15], dtype=np.int)

In [8]: arr2 = np.array(arr1, dtype=np.float)

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

Or you can use the astype method of numpy array.

In [10]: arr2
Out[10]: array([ 5., 10., 15.])

In [11]: arr2.astype(np.int)
Out[11]: array([ 5, 10, 15])

When doing computation with numpy array the data type might be converted from one type to another if it is required by the computation.

In [12]: arr1 = np.array([5, 10, 15], dtype=np.float)

In [13]: arr2 = np.array([5, 10, 15], dtype=np.complex)

In [14]: arr1 + arr2
Out[14]: array([10.+0.j, 20.+0.j, 30.+0.j])

Real and Imaginary parts –

Regardless of the dtype of a numpy array, all numpy arrays has the attributes real and imag for extracting the real and imaginary parts of the array.

In [15]: arr3 = np.array([5, 10, 15], dtype=np.int)

In [16]: arr3.real
Out[16]: array([ 5, 10, 15])

In [17]: arr3.imag
Out[17]: array([0, 0, 0])

Check numpy array data type –

To check the data type of a numpy array you can use the dtype attribute.

In [18]: arr4 = np.array([5, 10, 15])

In [19]: arr4.dtype
Out[19]: dtype('int32')

Related Posts –

  1. How to Create a Numpy array in Python
  2. Numpy array attributes with examples

Rating: 1 out of 5.

Leave a Reply