convert string representation of array to numpy array in python

Try this:

xs = '[0 1 2 3]'

import re, ast
ls = re.sub('\s+', ',', xs)
a = np.array(ast.literal_eval(ls))
a  # -> array([0, 1, 2, 3])    

For 1D arrays, Numpy has a function called fromstring, so it can be done very efficiently without extra libraries.

Briefly you can parse your string like this:

s = '[0 1 2 3]'
a = np.fromstring(s[1:-1], dtype=np.int, sep=' ')
print(a) # [0 1 2 3]

For nD arrays, one can use .replace() to remove the brackets and .reshape() to reshape to desired shape, or use Merlin's solution.

Tags:

Python

Numpy