gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:56:52 25 4
gpt4 key购买 nike

传递 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 字符串数据类型的匹配“类型标识符”。

# 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

只需要看看类型转换成本有多高。

最佳答案

对于 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)

关于python - 如何将字符串类型的 numpy 数组传递给 Cython 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11003037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com