传递ntype np.float64_t
的numpy数组工作正常(下图),但我无法传递字符串数组。
这是有效的:
# cython_testing.pyx
import numpy as np
cimport numpy as np
ctypedef np.float64_t dtype_t
cdef func1 (np.ndarray[dtype_t, ndim=2] A):
print A
def testing():
chunk = np.array ( [[94.,3.],[44.,4.]], dtype=np.float64)
func1 (chunk)
但我无法做到这一点: 我找不到numpy string dtypes匹配的'type identifier'。
# cython_testing.pyx
import numpy as np
cimport numpy as np
ctypedef np.string_t dtype_str_t
cdef func1 (np.ndarray[dtype_str_t, ndim=2] A):
print A
def testing():
chunk = np.array ( [['huh','yea'],['swell','ray']], dtype=np.string_)
func1 (chunk)
编译错误是:
Error compiling Cython file:
------------------------------------------------------------
ctypedef np.string_t dtype_str_t
^
------------------------------------------------------------
cython_testing.pyx:9:9: 'string_t' is not a type identifier
更新
通过查看numpy.pxd
,我看到以下ctypedef
语句。也许这足以说我可以使用uint8_t
并假装一切正常,只要我可以做一些演员?
ctypedef unsigned char npy_uint8
ctypedef npy_uint8 uint8_t
只需看看铸造的成本有多高。
答案 0 :(得分:7)
看起来你运气不好。
http://cython.readthedocs.org/en/latest/src/tutorial/numpy.html
尚不支持某些数据类型,如布尔数组和字符串数组。
这个答案不再有效,正如Saullo Castro的答案所示,但我会将其留作历史用途。
答案 1 :(得分:7)
使用Cython 0.20.1,它可以使用cdef np.ndarray
,而无需指定数据类型和维数:
import numpy as np
cimport numpy as np
cdef func1(np.ndarray A):
print A
def testing():
chunk = np.array([['huh','yea'], ['swell','ray']])
func1(chunk)