2
我之前已经做了一些numpy的C-扩展与很大的帮助,从这个site,但据我可以看到返回的参数都是固定的长度。在Numpy C扩展中返回可变长度数组?
是否有任何办法有一个numpy的C-延伸返回一个可变长度numpy的数组代替?
我之前已经做了一些numpy的C-扩展与很大的帮助,从这个site,但据我可以看到返回的参数都是固定的长度。在Numpy C扩展中返回可变长度数组?
是否有任何办法有一个numpy的C-延伸返回一个可变长度numpy的数组代替?
您可能会发现更容易使使用numpy的C-API,它简化了工艺,因为它允许你混合Python和C对象在用Cython numpy的扩展。在这种情况下,制作可变长度的数组并不困难,您可以简单地指定一个具有任意形状的数组。
的Cython numpy tutorial大概是关于这一主题的最佳来源。
例如,这里是一个功能我最近写道:
import numpy as np
cimport numpy as np
cimport cython
dtype = np.double
ctypedef double dtype_t
np.import_ufunc()
np.import_array()
def ewma(a, d, axis):
#Calculates the exponentially weighted moving average of array a along axis using the parameter d.
cdef void *args[1]
cdef double weight[1]
weight[0] = <double>np.exp(-d)
args[0] = &weight[0]
return apply_along_axis(&ewma_func, np.array(a, dtype = float), np.double, np.double, False, &(args[0]), <int>axis)
cdef void ewma_func(int n, void* aData,int astride, void* oData, int ostride, void** args):
#Exponentially weighted moving average calculation function
cdef double avg = 0.0
cdef double weight = (<double*>(args[0]))[0]
cdef int i = 0
for i in range(n):
avg = (<double*>((<char*>aData) + i * astride))[0]*weight + avg * (1.0 - weight)
(<double*>((<char*>oData) + i * ostride))[0] = avg
ctypedef void (*func_1d)(int, void*, int, void*, int, void **)
cdef apply_along_axis(func_1d function, a, adtype, odtype, reduce, void** args, int axis):
#generic function for applying a cython function along a particular dimension
oshape = list(a.shape)
if reduce :
oshape[axis] = 1
out = np.empty(oshape, odtype)
cdef np.flatiter ita, ito
ita = np.PyArray_IterAllButAxis(a, &axis)
ito = np.PyArray_IterAllButAxis(out, &axis)
cdef int axis_length = a.shape[axis]
cdef int a_axis_stride = a.strides[axis]
cdef int o_axis_stride = out.strides[axis]
if reduce:
o_axis_stride = 0
while np.PyArray_ITER_NOTDONE(ita):
function(axis_length, np.PyArray_ITER_DATA (ita), a_axis_stride, np.PyArray_ITER_DATA (ito), o_axis_stride, args)
np.PyArray_ITER_NEXT(ita)
np.PyArray_ITER_NEXT(ito)
if reduce:
oshape.pop(axis)
out.shape = oshape
return out
如果不适合你,还有用于制造新的空数组任意形状(link)的功能。
你怎么称其为“可变长度numpy的数组”?据我所知,numpy数组一旦设置大小就不能调整大小。 – albertov 2011-01-07 14:04:46