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"
.
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.
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.
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.
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.
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).
print "".join([chr(item) for item in a])
output
abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With