【问题标题】:How to pass a numpy array of string types to a function in Cython如何将字符串类型的 numpy 数组传递给 Cython 中的函数
【发布时间】:2012-06-12 18:59:10
【问题描述】:

传递一个 dtype 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 字符串 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)

编译错误是:

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

只需要看看这个选角会有多贵。

【问题讨论】:

    标签: python numpy cython


    【解决方案1】:

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

    【讨论】:

    • @TedPetrou 我正在尝试构建一个示例,其中dtype=object 将加速以更新答案,但到目前为止我发现它等同于不指定dtype。您是如何测量 100 倍速度的?
    • 看起来我在之前的评论中严重错误。看起来我通过更改为对象获得了 5 倍的改进。使用这个数组。 a = np.array(['some', 'strings', 'in', 'an', 'array'] * 10 ** 5)
    【解决方案2】:

    看来你运气不好。

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

    尚不支持某些数据类型,例如布尔数组和字符串数组。


    如 Saullo Castro 的回答所示,此答案不再有效,但出于历史目的,我将保留它。

    【讨论】:

    • 谢谢。我赞成你的回答。虽然我希望可以通过使用 Numpy 结构化数组 [docs.scipy.org/doc/numpy/user/… 来解决问题。但我仍在寻找如何通过其中之一。
    • 至少就我的目的而言,使用 cProfile,看起来您仍然可以在 Cython 中传递 Numpy 数组而无需输入。但是您没有获得 readthedocs.org 参考中描述的 Cython 优化。
    • 能慢慢用总比不能用好,对吧?
    • 此链接的内容已被修改。报价不存在。
    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2016-12-08
    相关资源
    最近更新 更多