David Eyk
David Eyk

Reputation: 12521

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

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.

Upvotes: 5

Views: 4295

Answers (3)

Anton
Anton

Reputation: 298

An update to Mike Graham's answer:

  1. numpy.fromstring is depreciated and should be replaced by numpy.frombuffer
  2. in case of complex numbers dtype should be defined explicitly

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]])

Upvotes: 0

Mike Graham
Mike Graham

Reputation: 76663

>>> 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.   ]])

Upvotes: 11

michel-slm
michel-slm

Reputation: 9756

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

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) ])

Upvotes: 0

Related Questions