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?
You don't need
nditerto iterate through this array:nditerjust makes life more complicated, and isn't any faster, especially for something likeprint. Who or what recommendednditer?For that matter, you can simply print the array:
But let's look at something else - the
idof elements of this object dtype array:You made an array with 10 references to the same tuple. Is that what you intended? It's the
fullthat has done that.To make a different tuple in each slot, I was going to suggest this list comprehension, but then realized it just produced a 2d array:
To make an object dtype array with actual tuples (different) we have to do something like:
But that brings us back to the basic question - why make an array of tuples in the first place? What's the point.
numpyis best with multidimensional numeric arrays. Object dtype array are, in many ways, just glorified (or debased) lists.