Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy array to tuple

Tags:

python

numpy

People also ask

Can you convert NumPy array to DataFrame?

To convert an array to a dataframe with Python you need to 1) have your NumPy array (e.g., np_array), and 2) use the pd. DataFrame() constructor like this: df = pd. DataFrame(np_array, columns=['Column1', 'Column2']) . Remember, that each column in your NumPy array needs to be named with columns.

How do you convert a 2d array to a tuple?

To convert Python tuple to array, use the np. asarray() function. The np. asarray() is a library function that converts input to an array.

Can you convert NumPy array to list in Python?

With NumPy, [ np. array ] objects can be converted to a list with the tolist() function. The tolist() function doesn't accept any arguments. If the array is one-dimensional, a list with the array elements is returned.


>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))

Here's a function that'll do it:

def totuple(a):
    try:
        return tuple(totuple(i) for i in a)
    except TypeError:
        return a

And an example:

>>> array = numpy.array(((2,2),(2,-2)))
>>> totuple(array)
((2, 2), (2, -2))

I was not satisfied, so I finally used this:

>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])

>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)

I don't know if it's quicker, but it looks more effective ;)


Another option

tuple([tuple(row) for row in myarray])

If you are passing NumPy arrays to C++ functions, you may also wish to look at using Cython or SWIG.