Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert a list of tupes to a numpy array of tuples?

I have a list like this:

l=[(1,2),(3,4)]

I want to convert it to a numpy array,and keep array item type as tuple:

array([(1,2),(3,4)])

but numpy.array(l) will give:

array([[1,2],[3,4)]])

and item type has been changed from tuple to numpy.ndarray,then I specified item types

numpy.array(l,numpy.dtype('float,float'))

this gives:

 array([(1,2),(3,4)])

but item type isn't tuple but numpy.void,so question is:

 how to convert it to a numpy.array of tuple,not of numpy.void? 
like image 306
Alex Luya Avatar asked Nov 20 '17 10:11

Alex Luya


People also ask

Can you have a NumPy array of tuples?

NumPy arrays can be defined using Python sequences such as lists and tuples.


1 Answers

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
like image 84
Divakar Avatar answered Sep 20 '22 18:09

Divakar