4

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?

4
  • np.array(literal_eval(s)) Commented Dec 3, 2014 at 0:01
  • Where did you get these strings from? If you've got some code that printing out or otherwise stringifying a bunch of lists or arrays for you to convert back later, it's almost always better to keep the lists or arrays themselves than to convert them back and forth. Commented Dec 3, 2014 at 1:11
  • @abarnert that would for sure be better, but I'm working with published data that happens to come in this format, so no way around it in this case. Commented Dec 3, 2014 at 9:14
  • @jacob: Even then, it's important to know the actual language of the published data so you know what it's intended to mean. If it's the output of a Python repr call, then literal_eval is the exact right way to reverse that. If it's some other language which is usually but not always valid as Python source code, then using literal_eval is a bad idea. Sometimes the best you can do is guess, but that should never be your first recourse. Commented Dec 5, 2014 at 19:06

2 Answers 2

6

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

equally valid answer, of course! Can only accept one, so accepted the earlier one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.