【问题标题】:How to create a numpy record array from C如何从 C 创建一个 numpy 记录数组
【发布时间】:2010-09-17 21:23:28
【问题描述】:

在 Python 端,我可以创建新的 numpy 记录数组,如下所示:

numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])

如何在 C 程序中做同样的事情?我想我必须调用PyArray_SimpleNewFromDescr(nd, dims, descr),但是如何构造一个适合作为第三个参数传递给PyArray_SimpleNewFromDescrPyArray_Descr

【问题讨论】:

    标签: python c numpy


    【解决方案1】:

    使用PyArray_DescrConverter。这是一个例子:

    #include <Python.h>
    #include <stdio.h>
    #include <numpy/arrayobject.h>
    
    int main(int argc, char *argv[])
    {
         int dims[] = { 2, 3 };
         PyObject *op, *array;
         PyArray_Descr *descr;
    
         Py_Initialize();
         import_array();
         op = Py_BuildValue("[(s, s), (s, s)]", "a", "i4", "b", "U5");
         PyArray_DescrConverter(op, &descr);
         Py_DECREF(op);
         array = PyArray_SimpleNewFromDescr(2, dims, descr);
         PyObject_Print(array, stdout, 0);
         printf("\n");
         Py_DECREF(array);
         return 0;
    }
    

    感谢Adam Rosenfield 指向Guide to NumPy 的第13.3.10 节。

    【讨论】:

      【解决方案2】:

      请参阅Guide to NumPy,第 13.3.10 节。有很多不同的方法来制作描述符,尽管它不像写[('a', 'i4'), ('b', 'U5')]那么容易。

      【讨论】:

      • 谢谢,指南提到了PyArray_DescrConverter,它有效。我已经发布了一个示例作为单独的答案,因为它不适合评论。
      • @JoelVroom:我不知道原始链接发生了什么,但我很容易找到指向同一文档的另一个链接。
      猜你喜欢
      • 1970-01-01
      • 2017-03-17
      • 2017-12-30
      • 2016-10-27
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 2016-03-03
      相关资源
      最近更新 更多