Converting a numpy.ndarray to string
Use ndarray.tostring
-
my_string_numpy_array.tostring()
Sample output -
In [176]: my_string_numpy_array.tostring()Out[176]: 'My name is Aman Raparia'
Now some years later, np.fromstring()
is deprecated:
my_string_numpy_array = np.fromstring(my_string, dtype=np.uint8):1: DeprecationWarning: The binarymode of fromstring is deprecated, as it behaves surprisingly onunicode inputs. Use frombuffer instead
Use np.frombuffer()
instead. And switch back to the input with np.array2string()
.
import numpy as npmy_string = b"My name is Aman Raparia"my_string_numpy_array = np.frombuffer(my_string, dtype=np.uint8)np.array2string(my_string_numpy_array, formatter={'int':lambda x: chr(x).encode()}, separator='').strip('[]').encode()
Out: b'My name is Aman Raparia'
You can drop the .encode()
to get string directly. It is just added to get to the original input again, and np.frombuffer()
requires a byte formatted buffer.
If you have more than one item as output and then need to remove the []-brackets, see np.array2string not removing brackets around an array.