Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a numpy record array from C

Tags:

python

c

numpy

On the Python side, I can create new numpy record arrays as follows:

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

How do I do the same from a C program? I suppose I have to call PyArray_SimpleNewFromDescr(nd, dims, descr), but how do I construct a PyArray_Descr that is appropriate for passing as the third argument to PyArray_SimpleNewFromDescr?

like image 869
Vebjorn Ljosa Avatar asked Oct 18 '08 04:10

Vebjorn Ljosa


People also ask

What is a NumPy record array?

Record arrays are structured arrays wrapped using a subclass of ndarray, numpy. recarray, which allows field access by attribute on the array object, and record arrays also use a special datatype, numpy. record, which allows field access by attribute on the individual elements of the array.

Does NumPy use C?

NumPy is written in C, and executes very quickly as a result. By comparison, Python is a dynamic language that is interpreted by the CPython interpreter, converted to bytecode, and executed. While it's no slouch, compiled C code is always going to be faster.


1 Answers

Use PyArray_DescrConverter. Here's an example:

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

Thanks to Adam Rosenfield for pointing to Section 13.3.10 of the Guide to NumPy.

like image 125
Vebjorn Ljosa Avatar answered Oct 06 '22 14:10

Vebjorn Ljosa