I'm a relatively experienced Python programmer, but haven't written any C in a very long time and am attempting to understand Cython. I'm trying to write a Cython function that will operate on a column of a NumPy recarray.
The code I have so far is below.
recarray_func.pyx:
import numpy as np
cimport numpy as npcdef packed struct rec_cell0:np.float32_t f0np.int64_t i0, i1, i2def sum(np.ndarray[rec_cell0, ndim=1] recarray):cdef Py_ssize_t icdef rec_cell0 *cellcdef np.float32_t running_sum = 0for i in range(recarray.shape[0]):cell = &recarray[i]running_sum += cell.f0return running_sum
At the interpreter prompt:
array = np.recarray((100, ), names=['f0', 'i0', 'i1', 'i2'],formats=['f4', 'i8', 'i8', 'i8'])
recarray_func.sum(array)
This simply sums the f0
column of the recarray. It compiles and runs without a problem.
My question is, how would I modify this so that it can operate on any column? In the example above, the column to sum is hard coded and accessed through dot notation. Is it possible to change the function so the column to sum is passed in as a parameter?