Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate numpy array (of tuples) in list manner

I am getting an error TypeError: Iterator operand or requested dtype holds references, but the REFS_OK flag was not enabled when iterating numpy array of tuples as below:

import numpy as np

tmp = np.empty((), dtype=object)
tmp[()] = (0, 0)
arr = np.full(10, tmp, dtype=object)

for a, b in np.nditer(arr):
    print(a, b)

How to fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The error message actually tells you the problem and the fix: you’re attempting to iterate over an array of reference types (i.e. objects, dtype=object), but you didn’t enable np.nditer to iterate over reference types.

To fix that set the REFS_OK flag when calling np.nditer:

for x in np.nditer(arr, flags=["refs_ok"]):
    ...

Do note that there is also a second issue in your code. After making this fix, np.nditer is going to yield references a zero-dimensional array, which can’t be unpacked into a, b (even though that zero-dimensional array contains a 2-tuple). Instead, you can extract the tuple using .item() and and unpack it in the loop body:

for x in np.nditer(arr, flags=["refs_ok"]):
    a, b = x.item()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading