在C / C ++中遍历ndarray列

时间:2019-07-04 16:14:03

标签: c++ python-3.x numpy numpy-ndarray python-c-api

如何获取类似于以下python代码的PyArrayObject *视图?

# n-column array x
# d is the length of each column
print(x.shape)  # => (d, n)

by_column = [x[::,i] for i in range(x.shape[1])]

assert len(by_column) == n

print(by_column[n-1].shape)  # => (d,)

到目前为止,我的代码是这样:

// my_array is a PyArrayObject* 
std::vector<PyArrayObject*> columns = {};

npy_intp* dims = my_array->dimensions;
npy_intp* strides = my_array->strides;

std::vector<int> shape = {};
for (int i = 0; &dims[i] != strides; i++){
    shape.push_back(dims[i]);
}

switch (shape.size()) {
    case 1: {
        // handle 1D array by simply iterating
    }
    case 2: {
        int columns = shape[1];
        // What now?
    }
}

我在文档和源代码中都找不到在C / C ++中执行此操作的任何引用,您能举一个如何执行此操作的示例吗?

与std :: vector之类的东西相比,用于numpy的C / C ++ API似乎确实令人费解,而且该文档也不是初学者,因此任何对简单指南的引用也将受到赞赏。

1 个答案:

答案 0 :(得分:1)

您应该通过PyArray_NDIM之类的PyArray_XXX函数访问PyArrayObject的内部结构。要获取序列的内容,请使用带有元组键的PyObject_GetItem,在用例中,元组将以PySliceObject作为第一个元素。