将 numpy.str 类型的 np.ndarray 转换为 int32 类型的 np.ndarray 的最正确方法是什么?

What is the most proper way to convert a np.ndarray of type numpy.str to np.ndarray of type int32?

我有以下错误

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.

我正在尝试找到最清晰的方法将 strings 转换为 ints in the array.

首先,您可以创建一个字典,说明您希望如何为每个字母分配值:

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

然后你可以做列表理解来得到你想要的结果:

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

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

我会以这种方式将字符串转换为数组中的整数:

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')