convert string representation of array to numpy array in python

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.

Leave a Comment