I’m having a little trouble here,
I’m trying to convert a numpy.ndarray to string, I’ve already done that like this:
randomArray.tostring()
It works, but I’m wondering if I can transform it back to a numpy.ndarray.
What’s the best way to do this?
I’m using numpy 1.8.1
Context: The objective is to send the numpy.ndarray as a message in rabbitmq (pika library)
Advertisement
Answer
You can use the fromstring()
method for this:
arr = np.array([1, 2, 3, 4, 5, 6]) ts = arr.tostring() print(np.fromstring(ts, dtype=int)) >>> [1 2 3 4 5 6]
Sorry for the short answer, not enough points for commenting. Remember to state the data types or you’ll end up in a world of pain.
Note on fromstring
from numpy 1.14 onwards:
sep : str, optional
The string separating numbers in the data; extra whitespace between elements is also ignored.
Deprecated since version 1.14: Passing sep=”, the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.