How to get string value from numpy array?

When I store string data as characters in a numpy array and get the values ​​later, it always returns the value as b'x 'for the' x 'which I saved earlier. I am currently using a silly way to extract the value by doing str(some_array[row, col...]).lstrip("b'").rstrip("'")

, I believe there should be an easier way to do this. Somebody knows? Thank!

+3


source to share


1 answer


Based on your output, you are using Python 3 (where bytes

and str

are different types). This answer applies to arrays with dtype='S'

(bytestring); for dtype=str

or dtype='U'

they are saved as unicode strings (at least for python 3) and no problem.

The easiest way to do this is probably

str(some_array[row,col...],encoding='ascii')

      



Note that you can use other encodings instead of ascii (commonly used 'UTF-8'

), and which one is right depends on which one you used to enter your data into the numpy array. If you're using non-exotic alphanumeric characters, it doesn't matter. If you put str

into an array, numpy uses ascii to encode it, so unless you took too much effort to do something else, 'ascii'

should be correct.

(For reference, I found this answer helpful at fooobar.com/questions/95992 / ... )

+2


source







All Articles