Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a numpy.ndarray to string

Tags:

python

numpy

I have string

my_string = "My name is Aman Raparia"

which I converted to numpy array of ordinal values using the statement

my_string_numpy_array = np.fromstring(my_string, dtype=np.uint8)

Is there any way to get back the original string from the my_string_numpy_array?

like image 319
Aman Raparia Avatar asked Jun 23 '17 16:06

Aman Raparia


People also ask

How do I turn an array into a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I save a NumPy array to a text file?

Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.

Can NumPy array store strings?

The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.


2 Answers

Use ndarray.tostring -

my_string_numpy_array.tostring()

Sample output -

In [176]: my_string_numpy_array.tostring()
Out[176]: 'My name is Aman Raparia'
like image 187
Divakar Avatar answered Oct 19 '22 17:10

Divakar


The right answer for numpy is Divakar's ndarray.tostring.

An alternative is to use chr on each array element and join together (for a non numpy array for example):

>>> ''.join([chr(e) for e in my_string_numpy_array])
'My name is Aman Raparia'
like image 2
dawg Avatar answered Oct 19 '22 18:10

dawg