How convert a list of tupes to a numpy array of tuples?
You can have an array of object
dtype, letting each element of the array being a tuple, like so -
out = np.empty(len(l), dtype=object)
out[:] = l
Sample run -
In [163]: l = [(1,2),(3,4)]
In [164]: out = np.empty(len(l), dtype=object)
In [165]: out[:] = l
In [172]: out
Out[172]: array([(1, 2), (3, 4)], dtype=object)
In [173]: out[0]
Out[173]: (1, 2)
In [174]: type(out[0])
Out[174]: tuple
For some reason you can't simply do this if you're looking for a single line of code (even though Divakar's answer ultimately leaves you with dtype=object
):
np.array([(1,2),(3,4)], dtype=object)
Instead you have to do this:
np.array([(1,2),(3,4)], dtype="f,f")
"f,f"
signals to the array that it's receiving tuples of two floats (or you could use "i,i"
for integers). If you wanted, you could cast back to an object by adding .astype(object)
to the end of the line above).