Convert Array Of Lists To Array Of Tuples/triple
Solution 1:
Your 2d array is not a list of lists, but it readily converts to that
a.tolist()
As Jimbo shows, you can convert this to a list of tuples with a comprehension
(a map
will also work). But when you try to wrap that in an array, you get the 2d array again. That's because np.array
tries to create as large a dimensioned array as the data allows. And with sublists (or tuples) all of the same length, that's a 2d array.
To preserve tuples you have switch to a structured array. For example:
a = np.array([[0, 20, 1], [1,2,1]])
a1=np.empty((2,), dtype=object)
a1[:]=[tuple(i) for i in a]
a1
# array([(0, 20, 1), (1, 2, 1)], dtype=object)
Here I create an empty structured array with dtype object
, the most general kind. Then I assign values, using a list of tuples, which is the proper data structure for this task.
An alternative dtype is
a1=np.empty((2,), dtype='int,int,int')
....
array([(0, 20, 1), (1, 2, 1)],
dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])
Or in one step: np.array([tuple(i) for i in a], dtype='int,int,int')
a1=np.empty((2,), dtype='(3,)int')
produces the 2d array. dt=np.dtype([('f0', '<i4', 3)])
produces
array([([0, 20, 1],), ([1, 2, 1],)],
dtype=[('f0', '<i4', (3,))])
which nests 1d arrays in the tuples. So it looks like object
or 3 fields is the closest we can get to an array of tuples.
Solution 2:
not the great solution, but this will work:
# take from your sample
>>>a = np.array([[0, 20, 1], [1,2,1], [20,1,1]])
# construct an empty array with matching length
>>>b = np.empty((3,), dtype=tuple)
# manually put values into tuple and store in b
>>>for i,n inenumerate(a):
>>> b[i] = (n[0],n[1],n[2])
>>>b
array([(0, 20, 1), (1, 2, 1), (20, 1, 1)], dtype=object)
>>>type(b)
numpy.ndarray
Post a Comment for "Convert Array Of Lists To Array Of Tuples/triple"