Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore a 2-dimensional numpy.array from a bytestring?

Tags:

python

numpy

numpy.array has a handy .tostring() method which produces a compact representation of the array as a bytestring. But how do I restore the original array from the bytestring? numpy.fromstring() only produces a 1-dimensional array, and there is no numpy.array.fromstring(). Seems like I ought to be able to provide a string, a shape, and a type, and go, but I can't find the function.

like image 947
David Eyk Avatar asked Aug 23 '11 17:08

David Eyk


1 Answers

>>> x
array([[ 0.   ,  0.125,  0.25 ],
       [ 0.375,  0.5  ,  0.625],
       [ 0.75 ,  0.875,  1.   ]])
>>> s = x.tostring()
>>> numpy.fromstring(s)
array([ 0.   ,  0.125,  0.25 ,  0.375,  0.5  ,  0.625,  0.75 ,  0.875,  1.   ])
>>> y = numpy.fromstring(s).reshape((3, 3))
>>> y
array([[ 0.   ,  0.125,  0.25 ],
       [ 0.375,  0.5  ,  0.625],
       [ 0.75 ,  0.875,  1.   ]])
like image 59
Mike Graham Avatar answered Sep 30 '22 13:09

Mike Graham