简体   繁体   English

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

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

I am trying to do handwritten digit recognition using K-Nearest Neighbours classification using scikit learn. 我正在尝试使用scikit Learn使用K最近邻分类进行手写数字识别。 I am creating my own dataset, and have a list of labels (where the labels are strings). 我正在创建自己的数据集,并具有标签列表(其中标签为字符串)。 The length of the list is 5000. 列表的长度是5000。

However, to do KNN classification, both the image data and labels have to be in numpy ndarrays. 但是,要进行KNN分类,图像数据和标签都必须位于numpy ndarrays中。 How can I convert a list of strings into a NumPy ndarray containing those strings? 如何将字符串列表转换为包含这些字符串的NumPy ndarray? Any insights are appreciated. 任何见解都表示赞赏。

just use the np.array() function as follows: 只需使用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))

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM