2011-01-07 55 views
2

我之前已經做了一些numpy的C-擴展與很大的幫助,從這個site,但據我可以看到返回的參數都是固定的長度。在Numpy C擴展中返回可變長度數組?

是否有任何辦法有一個numpy的C-延伸返回一個可變長度numpy的數組代替?

+2

你怎麼稱其爲「可變長度numpy的數組」?據我所知,numpy數組一旦設置大小就不能調整大小。 – albertov 2011-01-07 14:04:46

回答

3

您可能會發現更容易使使用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)的功能。