文字列を含む 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)。