ex1led
ex1led

Reputation: 469

NumPy np.chararray to nd.array

I have the following np.chararray

array = np.chararray(shape=(5))
initialize_array(array) 
# Gives out the following array of type S1
# [b'1' b'0' b'1' b'0' b'1'] 

How can I cast this array to a nd array? I wish for an array like

[ 1 0 1 0 1 ] # dtype = int 

Is this possible via some function that I am not aware of? Or should I do it by "hand"?


Using astype like:

new_ndarray = array.astype("int")

Raises a ValueError:

ValueError: Can only create a chararray from string data.

MCVE

#!/usr/bin/python3
import numpy as np

char_array = np.chararray(shape=(5))
char_array[:] = [b'1',b'0',b'1',b'0',b'1']
nd_array = char_array.astype("int")

Upvotes: 2

Views: 634

Answers (1)

javidcf
javidcf

Reputation: 59731

You can do:

import numpy as np
array = np.chararray(shape=(5))
array[:] = [b'1', b'0', b'1', b'0', b'1']
array_int = np.array(array, dtype=np.int32)
print(array_int)
# [1 0 1 0 1]

Upvotes: 4

Related Questions