Home > Back-end >  What is the most proper way to convert a np.ndarray of type numpy.str to np.ndarray of type int32?
What is the most proper way to convert a np.ndarray of type numpy.str to np.ndarray of type int32?

Time:04-12

I've the following error

TypeError: can't convert np.ndarray of type numpy.str_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

and I am trying to find the most clearest way to convert strings into ints in the array.

CodePudding user response:

Firstly, you can create a dictionary on how you want to assign each alphabet with the value:

dictionary = {'N':1,'S':2,'V':3}

Then you can do list comprehension to get your desired result:

result = [dictionary[i] for i in array]

np.count_nonzero(np.array(result) == 2)
Out[32]: 1

CodePudding user response:

I would convert strings into integers in an array in this way:

import numpy as np

# Let's create our numpy array of strings
letters_list = ['A','B','C','A']
letters_array = np.array(letters_list) 

#Let's create the corresponding list of integers
numbers_list = []
for i in letters_array:
    if i == 'A':
        numbers_list.append(1)
    elif i == 'B':
        numbers_list.append(2)
    else:
        numbers_list.append(3)

#Let's convert the list of integers into numpy array
numbers_array = np.array(numbers_list, dtype=np.int32)
numbers_array #array([1, 2, 3, 1])
numbers_array.dtype #dtype('int32')
 
  • Related