I have an array of tuple, for example like this array([[(), (6,), (8,6), ()]])
with a shape of (1, 4)
and I want to convert the tuples into strings array([['()', '(6,)', '(8,6)', '()']])
. What's the best way to do that? Thanks
CodePudding user response:
Use map
function:
In [1]: array = np.array([[(), (1,2), (8,6), ()]], dtype=object)
In [2]: np.array([list(map(str, array[0]))])
Out[2]: array([['()', '(1, 2)', '(8, 6)', '()']], dtype='<U6')
map
function, iterates through an interable and runs the function on all items inside it and finally. It returns a generator; So if you want to get a list, you have to use a list comprehension or list
function.
CodePudding user response:
You can make a vectorized version of the str constructor and then use it on the array:
import numpy as np
a = np.array([[(), (6,), (8,6), ()]])
asString = np.vectorize(str)
print(asString(a))
[['()' '(6,)' '(8, 6)' '()']]