NumPy: Iterating Array With Different Data Types

There comes a time when we want to treat an array as a different data type than it's stored.

In NumPy, it is not possible to change the data type of that element where the element is in that array. So we need to allocate some extra space to perform this action, that extra space is called a buffer, and to enable it in nditer() we need to pass flags=['buffered']. We can also use the op_dtypes argument, and pass it to change the datatypes of elements while iterating.

Example:

Converting Integer to Float:

import numpy as np
a=np.array([1,2,3])
for x in np.nditer(a,flags=['buffered'],op_dtypes=['float']):
    print(x)

Output:

1.0
2.0
3.0

Converting Integer to Complex:

import numpy as np
a=np.array([4,5,6])
for x in np.nditer(a,flags=['buffered'],op_dtypes=['complex128']):
    print(x)

Output:

(4+0j)
(5+0j)
(6+0j)

Converting Integer to String:

import numpy as np
a=np.array([4,5,6])
for x in np.nditer(a,flags=['buffered'],op_dtypes=['S']):
    print(x)

Output:

b'4'
b'5'
b'6'
Thu, 09/09/2021 - 21:41

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.