Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert unicode array to numpy

I have arrays of unicode strings like this

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

and need to convert these to numpy arrays. A similar question treats 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 of directly converting this to a numpy array (of ints) without having to manually remove the brackets?

like image 350
jacob Avatar asked Mar 17 '23 18:03

jacob


2 Answers

You could use literal_eval

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

arr= np.array(literal_eval(s))
like image 78
Padraic Cunningham Avatar answered Mar 20 '23 08:03

Padraic Cunningham


You could use literal_eval as follows:

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]]
like image 28
Marcin Avatar answered Mar 20 '23 08:03

Marcin