Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Numpy array of ASCII codes to string

Tags:

python

numpy

I would like to convert a NumPy array of integers representing ASCII codes to the corresponding string. For example ASCII code 97 is equal to character "a". I tried:

from numpy import *
a=array([97, 98, 99])
c = a.astype('string')
print c

which gives:

['9' '9' '9']

but I would like to get the string "abc".

like image 434
Håkon Hægland Avatar asked Jul 19 '14 08:07

Håkon Hægland


People also ask

How do you print ascii to string in Python?

Here are few methods in different programming languages to print ASCII value of a given character : Python code using ord function : ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord('a') returns the integer 97.

How do you convert ascii to character in Python?

chr () is a built-in function in Python that is used to convert the ASCII code into its corresponding character. The parameter passed in the function is a numeric, integer type value. The function returns a character for which the parameter is the ASCII code.

What is Astype Numpy?

Practical Data Science using Python We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array. We can check the type of numpy array using the dtype class.


3 Answers

import numpy as np
np.array([97, 98, 99], dtype='b').tobytes().decode("ascii")

Output:

'abc'

Data type objects (dtype)

tostring() is deprecated since version 1.19.0. Use tobytes() instead.

like image 80
ivanbgd Avatar answered Sep 17 '22 22:09

ivanbgd


Another solution that does not involve leaving the NumPy world is to view the data as strings:

arr = np.array([97, 98, 99], dtype=np.uint8).view('S3').squeeze()

or if your numpy array is not 8-bit integers:

arr = np.array([97, 98, 99]).astype(np.uint8).view('S3').squeeze()

In these cases however you do have to append the right length to the data type (e.g. 'S3' for 3 character strings).

like image 44
coderforlife Avatar answered Sep 16 '22 22:09

coderforlife


print "".join([chr(item) for item in a])

output

abc
like image 44
Ashoka Lella Avatar answered Sep 19 '22 22:09

Ashoka Lella