我正在尝试使用 NumPy 字符串数组作为 cython 函数的输入。但是,我似乎无法弄清楚如何在 cython 中实际使用 numPy 字符串数组。
这是我尝试用作函数输入的数组示例:
np.array(['foo', 'bar', 'baz', 'foo', 'bar'])
尝试 1:
#cython: language_level=3
import numpy as np
cimport numpy as np
cimport cython
def test_print(np.ndarray[str, ndim=1] unique_product_uids_np):
cdef str key
for key in unique_product_uids_np:
print(key)
上面的代码可以编译,但是当你尝试使用这个函数时,你会得到以下错误
arr = np.array(['foo', 'bar', 'baz', 'foo', 'bar'])
does_this_work.test_print(arr)
不理解字符缓冲区 dtype 格式字符串('w')
尝试 2:
#cython: language_level=3
import numpy as np
cimport numpy as np
cimport cython
def test_print(np.ndarray[np.str_, ndim=1] unique_product_uids_np):
cdef np.str_ key
for key in unique_product_uids_np:
print(key)
Error when compiling:
def test_print(np.ndarray[np.str_, ndim=1] unique_product_uids_np):
^
does_this_work.pyx:6:33: Invalid type.
我对
unicode
做了完全相同的测试并得到了与上面相同的结果。 unicode
编译但抛出 Does not understand character buffer dtype format string ('w')
和 np.unicode_
没有编译并在编译时抛出 Invalid type
错误。
这是我的
setup.py
文件的样子
from distutils.core import setup
from Cython.Build import cythonize
import numpy
setup(ext_modules = cythonize('does_this_work.pyx', annotate=True),
compiler_directives={'language_level' : "3"},
include_dirs=[numpy.get_include()])
这是我用来编译的命令:
python setup.py build_ext --inplace
我正在使用: Python 版本 3.10, Cython 版本 0.29.33, NumPy 版本 1.24.2