Skip to content Skip to sidebar Skip to footer

How To Convert Numpy Array Into Tuple

I need to convert array like this: [[1527 1369 86 86] [ 573 590 709 709] [1417 1000 68 68] [1361 1194 86 86]] to like this: [(726, 1219, 1281, 664),

Solution 1:

The array method tolist is a easy and fast way of converting an array to a list. It handles multiple dimensions correctly:

In [92]: arr = np.arange(12).reshape(3,4)
In [93]: arr
Out[93]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [94]: arr.tolist()
Out[94]: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

For most purposes such as list of lists is just as good as a list of tuples, or tuple of tuples. They differ only in mutability.

But if you must have a tuples, a list comprehension does the conversion nicely.

In[95]: [tuple(x) for x in arr.tolist()]Out[95]: [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]

An alternative [tuple(x) for x in arr] is a bit slower, because it is iterating on the array rather than on a list. It also produces a different result - though you have to examine the type of the tuple elements to see that.

I strongly recommend starting with the tolist method, and doing any list to tuple conversions after.

Solution 2:

What about using tuble and map function like this:

import numpy
numpy_arr = numpy.array(((1527, 1369,   86,   86),(573 , 590 , 709,  709)))
converted_list = tuple(map(tuple,numpy_arr)) # as list
converted_arr = map(tuple,numpy_arr) #as arrayprint(converted_arr)

Solution 3:

Here is the following function assuming you do not want the final object to be a numpy object.

def fun(var):
  a=[]
  for i invar:
    a.append(tuple(i))
  return a

if you want in one line

def fun(var):
  return [tuple(i) for i invar]

Solution 4:

If you prefer list comprehensions to map():

a = numpy.random.uniform(0,1,size=(4,4))
a_tuple_list = [tuple(row) for row in a]

Post a Comment for "How To Convert Numpy Array Into Tuple"