Python ord() equivalent in NumPy

Viewed 525

In Python, to get the ASCII value of a character we can do:

>>> x = ord('k')
>>> x
107

What is the equivalent Python "ord" method in NumPy? I see some solutions say to do hacks like list comprehension before passing it NumPy. However, I want a NumPy method to do the conversion. It seems there is not a way. Is there? Again, I don't want list comprehension, map, or lambda or other work-arounds. Those are all Python methods. I'm looking for the equivalent NumPy function.

EDIT: Based on Hilbert's comment, I want to convert NumPy array "x" to the ASCII equivalent using vectorized operations:

>>> a = ['g', 'h', 'i', 'j']
>>> x = np.array(a)
>>> x
array(['g', 'h', 'i', 'j'], dtype='<U1')
>>> 

So if "y" were my final array (after the conversion) it would look like this:

>>> y
array([103, 104, 105, 106])
>>> type(y)
<class 'numpy.ndarray'>
>>> 
1 Answers

numpy.ndarray.view returns a view of the same array with another (equally sized) datatype, and should due to not copying anything pretty much be instantaneous.

>>> x = np.array(['g', 'h', 'i', 'j'])
>>> x
array(['g', 'h', 'i', 'j'], dtype='<U1')
>>> y = x.view(np.int32)
>>> y
array([103, 104, 105, 106], dtype=int32)

Being a view to the original data though, if you mutate the original array, be aware that you also mutate the view.

>>> x[2]='x'
>>> y
array([103, 104, 120, 106], dtype=int32)
Related