Python:如何使用 NumPy ndarray 创建字符串数组

Python: How to create an array of strings using NumPy ndarray

我正在尝试使用 scikit learn 使用 K-最近邻分类进行手写数字识别。我正在创建自己的数据集,并有一个标签列表(标签是字符串)。列表长度为5000.

但是,要进行 KNN 分类,图像数据和标签都必须在 numpy ndarrays 中。 如何将字符串列表转换为包含这些字符串的 NumPy ndarray?任何见解表示赞赏。

只需使用np.array()函数如下:

import numpy as np

string_list = ["hello", "world", "str3", "str4"]

string_ndarray = np.array(string_list)

print(string_ndarray)
print(type(string_ndarray))

输出:

['hello' 'world' 'str3' 'str4']
<class 'numpy.ndarray'>