Convert Unicode array to numpy

I have arrays of unicode strings like

u'[(12520, 12540), (16600, 16620)]'

      

and need to convert them to numpy arrays. A similar question addresses the problem of already having an array with unicode elements, but in my case the brackets are part of the string. Is there a way to directly convert this to a numpy array (ints) without having to manually remove the parentheses?

+3


source to share


2 answers


You can use literal_eval



from ast import literal_eval
import numpy as np
s=u'[(12520, 12540), (16600, 16620)]'

arr= np.array(literal_eval(s))

      

+5


source


You can use literal_eval like this:

import ast

my_str = u'[(12520, 12540), (16600, 16620)]'

my_nparray = np.array(ast.literal_eval(my_str))

print(my_nparray)

      



Results in:

[[12520 12540]
 [16600 16620]]

      

+1


source







All Articles