有没有一种方法可以将 Python 字符串转换为 NumPy 字符数组,其中每个字符都是其自己的数组元素,而无需先将字符串转换为列表?我有一个程序必须使用大量数据来执行此操作,并且我已将转换步骤本身确定为瓶颈,但我似乎找不到任何可以直接获取字符串并以这种方式转换它而无需先创建的 NumPy 函数通用 Python 列表。
请您参考如下方法:
IIUC,可以使用fromiter将 dtype 指定为长度 1 的 unicode。
>>> np.fromiter('abcdefg', (np.unicode,1))
如 official docs ,
The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations.
因此,如果您需要使用isalpha() 等方法,请使用np.char 模块,如下所示,而不是np.chararray类了:
>>> np.char.isalpha(x)
