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.
To convert Python tuple to array, use the np. asarray() function. The np. asarray() is a library function that converts input to an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With