为了账号安全,请及时绑定邮箱和手机立即绑定

从C扩展返回numpy数组

从C扩展返回numpy数组

杨__羊羊 2021-03-18 14:15:54
为了学习新的知识,我目前正在尝试在C中重新实现numpy.mean()函数。它应该采用3D数组,并返回2D数组,其元素沿轴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();}到目前为止,我所了解的(如果我错了,请纠正我)是我需要创建一个new PyArrayObject,这将是我的输出(也许带有PyArray_FromDims?)。然后,我需要一个地址数组到该数组的内存中,并用数据填充它。我将如何处理?
查看完整描述

2 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

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);

}


查看完整回答
反对 回复 2021-03-24
  • 2 回答
  • 0 关注
  • 300 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号