简体   繁体   English

如何将一个numpy字符串类型数组传递给Cython中的函数

[英]How to pass a numpy array of string types to a function in Cython

Passing a numpy array of dtype np.float64_t works fine ( below), but I can't pass string arrays. 传递np.float64_t的numpy数组工作正常(下面),但我无法传递字符串数组。

This is what works : 这是有效的:

# 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)

But I can't make this work: I can't find the matching 'type identifiers' for numpy string dtypes. 但我无法做到这一点:我找不到匹配的'类型标识符'为numpy字符串dtypes。

# 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)

The compilation error is : 编译错误是:

Error compiling Cython file:
------------------------------------------------------------
ctypedef np.string_t dtype_str_t 
    ^
------------------------------------------------------------

cython_testing.pyx:9:9: 'string_t' is not a type identifier

UPDATE UPDATE

Per looking through numpy.pxd , I see the following ctypedef statements. 通过numpy.pxd ,我看到以下ctypedef语句。 Maybe that's enough to say I can use uint8_t and pretend everything is normal, as long as I can do some casting? 也许这足以说我可以使用uint8_t并假装一切正常,只要我可以做一些演员?

ctypedef unsigned char      npy_uint8
ctypedef npy_uint8      uint8_t

Just have to see how expensive that casting will be. 只需看看铸造的成本有多高。

Looks like you're out of luck. 看起来你运气不好。

http://cython.readthedocs.org/en/latest/src/tutorial/numpy.html http://cython.readthedocs.org/en/latest/src/tutorial/numpy.html

Some data types are not yet supported, like boolean arrays and string arrays. 尚不支持某些数据类型,如布尔数组和字符串数组。


This answer is no longer valid as shown by Saullo Castro's answer, but I'll leave it for historical purposes. 这个答案已经不再有效,正如Saullo Castro的回答所示,但我会将其留作历史用途。

With Cython 0.20.1 it works using cdef np.ndarray , without specifying the data type and the number of dimensions: 使用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)

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

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