5

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.

David Eyk
  • 12,171
  • 11
  • 63
  • 103

3 Answers3

11
>>> 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.   ]])
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
0

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]])
Anton
  • 174
  • 1
  • 11
0

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) ])
michel-slm
  • 9,438
  • 3
  • 32
  • 31