How to change numpy array int values to chars?
Question:
I am trying to change the value of a numpy array with generated values to char :
np_array = np.random.randint(0, 255, 5)
for i in range(256):
np_array[sample_data == i] = chr(i)
However it gives me the error :
ValueError: invalid literal for int() with base 10: 'x00'
I’d assume that np.array is flexible like a list able to hold other values is that not case? does it work like a real array? do I need to create another variable that is a char, how do I do that without having a loop?
Answers:
You can use numpy.ndarray.view
method to view the integers as unicode characters.
Note:
Since you are generating integers without specifying their dtype
– it is selected automatically. It can be different on different systems, and you have to set it explicitly before calling .view
:
np_array = np_array.astype('uint32')
Alternatively, you can simply specify it when generating the integers, and then you won’t need to change it in the future:
np_array = np.random.randint(0, 255, 5, dtype='uint32')
To convert integers to unicode characters you can use either ‘U1’: 4 bytes, or ‘U2’: 8 bytes.
Here I’m setting the necessary dtype
just to be explicit:
np_array = np_array.astype('uint32').view('U1')
# or
np_array = np_array.astype('uint64').view('U2')
I am trying to change the value of a numpy array with generated values to char :
np_array = np.random.randint(0, 255, 5)
for i in range(256):
np_array[sample_data == i] = chr(i)
However it gives me the error :
ValueError: invalid literal for int() with base 10: 'x00'
I’d assume that np.array is flexible like a list able to hold other values is that not case? does it work like a real array? do I need to create another variable that is a char, how do I do that without having a loop?
You can use numpy.ndarray.view
method to view the integers as unicode characters.
Note:
Since you are generating integers without specifying their dtype
– it is selected automatically. It can be different on different systems, and you have to set it explicitly before calling .view
:
np_array = np_array.astype('uint32')
Alternatively, you can simply specify it when generating the integers, and then you won’t need to change it in the future:
np_array = np.random.randint(0, 255, 5, dtype='uint32')
To convert integers to unicode characters you can use either ‘U1’: 4 bytes, or ‘U2’: 8 bytes.
Here I’m setting the necessary dtype
just to be explicit:
np_array = np_array.astype('uint32').view('U1')
# or
np_array = np_array.astype('uint64').view('U2')