As an example:
from numpy import *
A = array([2/3., 4])
print A
Gives
[ 0.66666667 4. ]
How do I take the string:
S = "[ 0.66666667 4. ]"
And convert S back into A using numpy calls only? I have a hackish solution in place but it seems that there should be a numpy builtin that does this. I looked at fromstring, but when I used it directly it gives me the error:
fromstring(S)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: string size must be a multiple of element size
You need fromstring(S, sep=' '). You almost parsed the string as packed binary data instead of printable floats. The string should only contain numbers and the delimiter (space), so trim it to get rid of the brackets. E.g., S[1:-1].
You probably know this but let's spell it out: This may be handy for recovering the results of a computation (or recovering from a mistake), but it is not a good way to store and reload data. It is inconvenient and you lose precision in the conversion. Your functions should return an array instead of printing it out, and if you need to store data for use by a later program run, use a digital storage format (e.g., see the cPickle module or whatever numpy provides for the purpose-- note that fromstring can also read packed binary data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With