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.
Add a comment
|
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. ]])
1 Comment
David Eyk
Didn't know that was even possible. This is exactly what I was looking for. Thanks.
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
David Eyk
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!michel-lind
ah, you're right; serves me right for testing it on a test case where nrows = ndim = 2 ! Fixing the answer
Mike Graham
Using the
reshape method is more direct, readable, robust, and efficient than this, and less errorprone.David Eyk
Agreed, much more robust than this.
michel-lind
Good call. Likely much faster too!
An update to Mike Graham's answer:
numpy.fromstringis depreciated and should be replaced bynumpy.frombuffer- in case of
complexnumbersdtypeshould 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]])