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.

3 Answers 3

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.   ]])
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't know that was even possible. This is exactly what I was looking for. Thanks.
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) ])

5 Comments

ndim is a little misleading--that's specifying the number of rows, not the number of dimensions, by my reading. But it seems to work!
ah, you're right; serves me right for testing it on a test case where nrows = ndim = 2 ! Fixing the answer
Using the reshape method is more direct, readable, robust, and efficient than this, and less errorprone.
Agreed, much more robust than this.
Good call. Likely much faster too!
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]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.