0

我无法在包含字符串的 numpy 数组上生成内存视图。最终目标是将字符串转换为整数。在这两者之间,我必须使用将strtok指针作为参数的 c 函数在适当的位置拆分字符串。因此,我不能简单地从 numpy 数组中传递元素,而必须按照此处所述创建内存视图。

这是我的代码

from __future__ import division
import numpy as np
cimport numpy as np
cimport cython 

from libc.string cimport strtok
from libc.stdlib cimport strtod, atoi 

DTYPE = np.int
ctypedef np.int_t DTYPE_t

def str2int(string_array):

    if not string_array.flags['C_CONTIGUOUS']:
        string_array = np.ascontiguousarray(string_array)        

    cdef:
        int n = string_array.shape[0]
        char[::1] arr_memview = string_array
        char *token      
        np.ndarray[DTYPE_t, ndim=1] integer_time = np.zeros(n, dtype=DTYPE)
        np.ndarray[DTYPE_t, ndim=1] conv = np.array([60**2, 60, 1], dtype=DTYPE)
        int count, num 
        size_t i

    for i in range(n):

        token = strtok(&arr_memview[i], ':')

        count = 0
        num = 0
        while token!=NULL:
            num += atoi(token)*conv[count] 
            count +=1 
            token = strtok(NULL, ':')

        integer_time[i] = num

    return integer_time   

pxy 文件可以编译,但是当我尝试像这样使用它时

import numpy as np
from strings_to_integers import str2int

strarr = np.array(['00:00:01','00:09:30'], dtype=str)
converted = str2int(strarr)

我收到一条错误消息char[::1] arr_memview = string_array: ValueError: Buffer dtype mismatch, expected end but got a string。(以后可能会出现更多错误。)

我认为这里以某种方式提供了我的问题的答案,但我不太了解它,无法让我的代码正常工作。例如,当我将有问题的行char[:,::1] arr_memview = string_array更改为并将循环中的第一行更改为token = strtok(&arr_memview[i,0], ':')我收到错误时ValueError: Buffer has wrong number of dimensions (expected 2, got 1)

4

0 回答 0