咨询Python中numpy数组式索引操作对应的C-API名称
实现Numpy数组索引的C-API方法
你需要的是实现整数数组索引(即a[[1,3,5]])的Numpy C-API,核心可用以下两个方法:
1. PyArray_Take(推荐直接使用)
这是最直接对应你需求的API,专门用于从数组按索引提取元素,函数原型:
PyObject *PyArray_Take(PyArrayObject *arr, PyObject *indices, int axis, PyObject *out, int mode, PyObject *fill_value)
参数与功能说明
- 功能:从输入数组
arr的指定维度axis上,按照indices中的索引值提取元素,返回新数组(或写入out指定的数组)。你的一维数组场景下axis设为0即可。 - 参数解析:
arr:输入的Numpy数组对象(PyArrayObject*类型)indices:索引对象,可以是Python列表或Numpy数组,对应你示例中的[1,3,5]axis:要提取元素的维度,一维数组传0out:可选参数,指定输出数组(传NULL则自动创建新数组)mode:越界索引处理模式,常用值:NPY_RAISE:索引越界时抛出错误(你的示例场景适用)NPY_WRAP:循环使用索引(如索引超出长度则从开头重新计数)NPY_CLIP:将越界索引截断到数组边界
fill_value:仅当mode为NPY_PAD时使用的填充值,其他模式传NULL
简单C代码示例
#include <Python.h> #include <numpy/arrayobject.h> static PyObject* array_index_example(PyObject* self, PyObject* args) { PyArrayObject *input_arr, *index_arr; // 解析输入参数:两个Numpy数组 if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &input_arr, &PyArray_Type, &index_arr)) { return NULL; } // 执行索引提取:一维数组axis=0,越界报错,不指定输出数组和填充值 PyObject *result = PyArray_Take(input_arr, (PyObject*)index_arr, 0, NULL, NPY_RAISE, NULL); return result; }
2. PyArray_GetItem(通用索引方法)
这是更通用的数组元素获取API,支持所有Numpy索引方式(包括整数数组索引、切片等)。使用时需要将索引包装成Python元组(即使是一维索引,也要用元组包裹):
代码示例
#include <Python.h> #include <numpy/arrayobject.h> static PyObject* generic_index_example(PyObject* self, PyObject* args) { PyArrayObject *input_arr, *index_arr; if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &input_arr, &PyArray_Type, &index_arr)) { return NULL; } // 创建索引元组:一维索引需要包裹成长度为1的元组 PyObject *index_tuple = PyTuple_New(1); PyTuple_SetItem(index_tuple, 0, (PyObject*)index_arr); // 元组会接管index_arr的引用 // 执行索引操作 PyObject *result = PyArray_GetItem(input_arr, index_tuple); // 释放元组对象 Py_DECREF(index_tuple); return result; }
内容的提问来源于stack exchange,提问作者dongrixinyu
相关产品推荐
相关产品推荐

