I recently found out how to use tuples thanks to great contributions from SO users(see here). However I encounter the problem that I can’t add a tuple to another tuple stored inside an array of tuples. For instance if I define:
arrtup=empty((2,2),dtype=('int,int'))
arrtup[0,1]=(3,4)
Then if I try to add another tuple to the existing tupe to come up with a multidimensional index:
arrtup[0,1]+(4,4)
I obtain this error:
TypeError: unsupported operand type(s) for +: 'numpy.void' and 'tuple'
Instead of the expected (3,4,4,4) tuple, which I can obtain by:
(3,4)+(4,4)
Any ideas? Thanks!
You are mixing different concepts, I’m afraid.
Your
arrtuparray is not an array of tuples, it’s a structuredndarray, that is, an array of elements that look like tuples but in fact are records (numpy.voidobjects, to be exact). In your case, you defined these records to consist in 2 integers. Internally, NumPy creates your array as a 2×2 array of blocks, each block taking a given space defined by yourdtype: here, a block consists of 2 consecutive blocks of sizeint(that is, each sub-block takes the space aninttakes on your machine).When you retrieve an element with
arrtup[0,1], you get the corresponding block. Because this block is structured as two-subblocks, NumPy returns anumpy.void(the generic object representing structured blocks), which has the samedtypeas your array.Because you set the size of those blocks at the creation of the array, you’re no longer able to modify it. That means that you cannot transform your 2-int records into 4-int ones as you want.
However, you can transform you structured array into an array of objects:
Lo and behold, your elements are no longer
np.voidbut tuples, that you can modify as you want:Your
new_arris a different beast from yourarrtup: it has the same size, true, but it’s no longer a structured array, it’s an array of objects, as illustrated byIn practice, the memory layout is quite different between
arrtupandnewarr.newarrdoesn’t have the same constraints asarrtup, as the individual elements can have different sizes, but object arrays are not as efficient as structured arrays.