python - 如何从 C 创建一个 numpy 记录数组

标签 python c numpy

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

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

如何从 C 程序执行相同的操作?我想我必须调用 PyArray_SimpleNewFromDescr(nd, dims, descr),但是我如何构造一个适合作为第三个参数传递给 PyArray_SimpleNewFromDescr 的 PyArray_Descr ?

最佳答案

使用 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 节.

关于python - 如何从 C 创建一个 numpy 记录数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/214549/

相关文章:

python - PyCharm 重新格式化代码不会将行换行至指定长度

c - `atomic_compare_exchange_strong_explicit()` -- 当不相等时,`success` 和 `failure` 参数的各种组合会做什么?

c - 分支与多线程

python - 升级到 scikit 0.15 时导入错误,numpy 警告

python - Numpy 已安装但仍然出现错误

python - 如何在numpy数组中选择轴值

python - 在 Python 中将 float.hex() 值转换为二进制

python - 选择仅包含字母字符的行

python - 比较两个字典列表并输出差异

c - 如何确定C中结构体的大小