The function numpy.array_repr
can be used to create a string representation of a NumPy array. How can a string representation of a NumPy array be converted to a Num
I often debug with print
statements. To read numpy output from the console back into a python environment, I use the following utility based on np.matrix.
def string_to_numpy(text, dtype=None):
"""
Convert text into 1D or 2D arrays using np.matrix().
The result is returned as an np.ndarray.
"""
import re
text = text.strip()
# Using a regexp, decide whether the array is flat or not.
# The following matches either: "[1 2 3]" or "1 2 3"
is_flat = bool(re.match(r"^(\[[^\[].+[^\]]\]|[^\[].+[^\]])$",
text, flags=re.S))
# Replace newline characters with semicolons.
text = text.replace("]\n", "];")
# Prepare the result.
result = np.asarray(np.matrix(text, dtype=dtype))
return result.flatten() if is_flat else result
Here's the workflow that I often apply for debugging:
1) Somewhere in my code...
import numpy as np
x = np.random.random((3,5)).round(decimals=2)
print(x)
[[0.24 0.68 0.57 0.37 0.83]
[0.76 0.5 0.46 0.49 0.95]
[0.39 0.37 0.48 0.69 0.25]]
In [9]: s2n = string_to_numpy # Short alias
In [10]: x = s2n("""[[0.24 0.68 0.57 0.37 0.83]
[0.76 0.5 0.46 0.49 0.95]
[0.39 0.37 0.48 0.69 0.25]]""")
In [11]: x.shape
Out[11]: (3, 5)
In [12]: x.mean(axis=1)
Out[12]: array([0.538, 0.632, 0.436])
...
eval
is the easiest, probably. It evaluates a given string as if it were code.
from numpy import array, all
arr_1 = array([1,2,3])
arr_string = repr(arr_1)
arr_2 = eval(arr_string)
all(arr_1 == arr_2) # True
See also documentation on eval
: https://docs.python.org/2/library/functions.html#eval