Pregunta

En el lado de Python, puedo crear nuevas matrices de registros numpy de la siguiente manera:

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

¿Cómo hago lo mismo desde un programa en C? Supongo que debo llamar a PyArray_SimpleNewFromDescr (nd, dims, descr) , pero ¿cómo construyo un PyArray_Descr que sea apropiado para pasar como tercer argumento a PyArray_SimpleNewFromDescr ?

¿Fue útil?

Solución

Utilice PyArray_DescrConverter . Aquí hay un ejemplo:

#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;
}

Gracias a Adam Rosenfield por señalar la Sección 13.3.10 de Guide to NumPy .

Otros consejos

Consulte la Guía de NumPy , sección 13.3 .10. Hay muchas maneras diferentes de hacer un descriptor, aunque no es tan fácil como escribir [('a', 'i4'), ('b', 'U5')] .

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top