How to read NumPy 2D array from string?
<p>How can I read a Numpy array from a string? Take a string like:</p>
<pre><code>&quot;[[ 0.5544  0.4456], [ 0.8811  0.1189]]&quot;
</code></pre>
<p>and convert it to an array:</p>
<pre><code>a = from_string(&quot;[[ 0.5544  0.4456], [ 0.8811  0.1189]]&quot;)
</code></pre>
<p>where <code>a</code> becomes the object: <code>np.array([[0.5544, 0.4456], [0.8811, 0.1189]])</code>.</p>
<p>I'm looking for a very simple interface. A way to convert 2D arrays (of floats) to a string and then a way to read them back to reconstruct the array:</p>
<p><code>arr_to_string(array([[0.5544, 0.4456], [0.8811, 0.1189]]))</code> should return <code>&quot;[[ 0.5544  0.4456], [ 0.8811  0.1189]]&quot;</code>.</p>
<p><code>string_to_arr(&quot;[[ 0.5544  0.4456], [ 0.8811  0.1189]]&quot;)</code> should return the object <code>array([[0.5544, 0.4456], [0.8811, 0.1189]])</code>.</p>
<p>Ideally <code>arr_to_string</code> would have a precision parameter that controlled the precision of floating points converted to strings, so that you wouldn't get entries like <code>0.4444444999999999999999999</code>.</p>
<p>There's nothing I can find in the NumPy docs that does this both ways. <code>np.save</code> lets you make a string but then there's no way to load it back in (<code>np.load</code> only works for files).</p>