Convert str(array) back to numpy array

Posted on Sun 21 May 2017 in Physics

If we print a numpy array, which actually use str(), we will find it almost irreversible.

In [5]:
l=arange(16).reshape(4,4)
print('l is printed as:\n', l)

l is printed as:
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]


Use print() will fallback to str(), so str() is not the correct way.

• repr()
• .tolist()
In [77]:
print('Array Form:\n', repr(l))
print('List form:\n', l.tolist())

Array Form:
array([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])
List form:
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]


If you really need to convert the array string separated by spaces into python, here is a remedy str2array():

In [21]:
import re
import ast
def array2str(arr, precision=None):
s=array_str(arr, precision=precision)
return s.replace('\n', ',')

def str2array(s):
# Remove space after [
s=re.sub('\[ +', '[', s.strip())
# Replace commas and spaces
s=re.sub('[,\s]+', ', ', s)
return array(ast.literal_eval(s))

In [20]:
str2array(array2str(sqrt(l), 3))

Out[20]:
array([[ 0.   ,  1.   ,  1.414,  1.732],
[ 2.   ,  2.236,  2.449,  2.646],
[ 2.828,  3.   ,  3.162,  3.317],
[ 3.464,  3.606,  3.742,  3.873]])