Search code examples
pythonnumpynumpy-ndarraypython-c-api

Numpy multi-slice using C API?


I know how to get a slice from a Numpy array using the C API this way:

    // 'arr' is a 2D Python array, already created
    PyObject pyArray = PyArray_FromAny(arr, PyArray_DescrFromType(NPY_FLOAT), 0, 0, NPY_ARRAY_DEFAULT, null);

    PyObject slice = PySlice_New(PyLong_FromLong(0), PyLong_FromLong(2), null);
    PyObject result = PyObject_GetItem(pyArray, slice);

This basically matches the following Python expression:

    arr[0:2]

Now, how can I get a "multi" slice from 'arr'? For instance, how can programmatically write the following expression?

    arr[0:2,0:3]

Solution

  • In order to get multi dimensional slices you have to insert the slices in a tuple, the call the get item on that tuple. Something like:

    PyObject* pyArray = PyArray_FromAny(arr, PyArray_DescrFromType(NPY_FLOAT), 0, 0, NPY_ARRAY_DEFAULT, null);
    
    PyObject* slice_0 = PySlice_New(PyLong_FromLong(0), PyLong_FromLong(2), null);
    PyObject* slice_1 = PySlice_New(PyLong_FromLong(0), PyLong_FromLong(3), null);
    PyObject* slices = PyTuple_Pack(2, slice_0, slice_1);
    
    PyObject* result = PyObject_GetItem(pyArray, slices);
    

    The rationale behind it is the __getitem__(self, arg) (there is a single argument) thus multiple indexes are implicitly converted in a tuple: arg = (slice(0,2), slice(0,3),)