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?
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))
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]]
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