从C扩展返回numpy数组

2024-10-01 11:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

为了学习新的东西,我目前正在尝试重新实现numpy.平均值()函数。它应该取一个三维数组,并返回一个二维数组,其中包含沿轴0的元素的平均值。我设法计算所有值的平均值,但不知道如何将新数组返回给Python。在

目前我的代码:

#include <Python.h>
#include <numpy/arrayobject.h>

// Actual magic here:
static PyObject*
myexts_std(PyObject *self, PyObject *args)
{
    PyArrayObject *input=NULL;
    int i, j, k, x, y, z, dims[2];
    double out = 0.0; 

    if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &input))
        return NULL;

    x = input->dimensions[0];
    y = input->dimensions[1];
    z = input->dimensions[2];

    for(k=0;k<z;k++){
        for(j=0;j<y;j++){
            for(i=0;i < x; i++){
                out += *(double*)(input->data + i*input->strides[0] 
+j*input->strides[1] + k*input->strides[2]);
            }
        }
    }
    out /= x*y*z;
    return Py_BuildValue("f", out);
}

// Methods table - this defines the interface to python by mapping names to
// c-functions    
static PyMethodDef myextsMethods[] = {
    {"std", myexts_std, METH_VARARGS,
        "Calculate the standard deviation pixelwise."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initmyexts(void)
{
    (void) Py_InitModule("myexts", myextsMethods);
    import_array();
}

到目前为止,我所理解的(如果我错了,请纠正我)是我需要创建一个新的PyArrayObject,这将是我的输出(可能使用PyArray_FromDims?)。然后我需要一个地址数组到这个数组的内存中,并用数据填充它。我该怎么做?在

编辑:

在对指针(这里:http://pw1.netcom.com/~tjensen/ptr/pointers.htm)进行了更多的阅读之后,我实现了我的目标。现在另一个问题出现了:在哪里可以找到numpy.平均值()? 我想看看python操作比我的版本快得多。我想它能避免难看的循环。在

我的解决方案是:

^{pr2}$

Tags: numpyforinputincludeargsstatic数组out
1条回答
网友
1楼 · 发布于 2024-10-01 11:27:49

Numpy API有一个函数PyArray_Mean,它可以在没有“难看的循环”的情况下完成您正在尝试的操作。

static PyObject *func1(PyObject *self, PyObject *args) {
    PyArrayObject *X, *meanX;
    int axis;

    PyArg_ParseTuple(args, "O!i", &PyArray_Type, &X, &axis);
    meanX = (PyArrayObject *) PyArray_Mean(X, axis, NPY_DOUBLE, NULL);

    return PyArray_Return(meanX);
}

相关问题 更多 >