How to recover 2-dimensional numpy.array from byte?

numpy.arrayhas a convenient method .tostring()that creates a compact representation of an array as a bytestring. But how to restore the original array from byte? numpy.fromstring()only creates a one-dimensional array, and no numpy.array.fromstring(). It looks like I would have to provide a string, form and type, and go, but I can not find the function.

+5
source share
3 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.   ]])
+11
source

It does not seem to exist; you can easily write it yourself:

def numpy_2darray_fromstring(s, nrows=1, dtype=float):
  chunk_size = len(s)/nrows
  return numpy.array([ numpy.fromstring(s[i*chunk_size:(i+1)*chunk_size], dtype=dtype)
                       for i in xrange(nrows) ])
0
source

Update Mike Graham's answer:

  1. numpy.fromstring and should be replaced by numpy.frombuffer
  2. in the case of complexnumbers it dtypemust be explicitly defined

So the above example would become:

>>> x = numpy.array([[1, 2j], [3j, 4]])
>>> x
array([[1.+0.j, 0.+2.j],
       [0.+3.j, 4.+0.j]])
>>> s = x.tostring()
>>> y = numpy.frombuffer(s, dtype=x.dtype).reshape(x.shape)
>>> y
array([[1.+0.j, 0.+2.j],
       [0.+3.j, 4.+0.j]])
0
source

All Articles