python - str object and string dtypes mismatch in Cython -
i'm trying run simple cython
code ipython notebook. have following code snippet:
%load_ext cythonmagic %%cython cimport cython import numpy np cimport numpy np cdef int test(np.ndarray[np.str, ndim = 1] a): return 6 print test(np.array(['gona','haraka']))
what want pass numpy 1d array of strings function. when function test
executed, returns 0 , following error:
exception valueerror: "buffer dtype mismatch, expected 'str object' got string" in '_cython_magic_505ff8c1b7497cde585006f723e794bd.test' ignored
what can reason this?
how pass numpy array of strings?
if use str
instead of np.str
or give dtype=np.str
in numpy array when function test
called, same error.
i tested cython 0.20.1 , can use general np.ndarray
definition, not specifying data type or number of dimensions:
cimport cython import numpy np cimport numpy np cdef int test(np.ndarray a): return 6 print test(np.array(['gona', 'haraka']))
if want better performance can pass numpy string array using pointer , passing array around through char *
buffer. following example shows how can achieved. increases character code adding 1 each non-zero value:
import numpy np cimport numpy np cdef int f(char *a, int size): cdef int in range(size): if a[i]!=0: a[i] += 1 def main(): cdef char *inp cdef np.ndarray = np.array(['aaaa', 'bbbbbb']) inp = a.data print f(inp, a.itemsize*a.shape[0]) print
when run main()
get:
['aaaa' 'bbbbbb'] ['bbbb' 'cccccc']
Comments
Post a Comment