how to convert numpy array into tuple

17,523

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

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

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

if you want in one line

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

Solution 3

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 array
print(converted_arr)
Share:
17,523
Karan Purohit
Author by

Karan Purohit

Updated on June 26, 2022

Comments

  • Karan Purohit
    Karan Purohit almost 2 years

    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),
        (1208, 1440, 1283, 1365), 
        (1006, 1483, 1069, 1421),
        (999, 1414, 1062, 1351),]
    

    I tried using convert diretly to tuple but got this:

             ( array([1527, 1369,   86,   86], dtype=int32), 
               array([573, 590, 709, 709], dtype=int32),
               array([1417, 1000,   68,   68], dtype=int32), 
               array([1361, 1194,   86,   86], dtype=int32))
               (array([701, 899, 671, 671], dtype=int32),)