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