如何获得类似于以下 python 代码的 PyArrayObject* View ?
# 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 似乎真的很复杂,而且文档对初学者也不是很友好,所以任何对更简单指南的引用也将不胜感激。
最佳答案
您应该通过 PyArray_XXX 函数访问 PyArrayObject 的内部结构,如 PyArray_NDIM .要获取序列的内容,请使用 PyObject_GetItem
使用元组键,在您的用例中,元组将 PySliceObject 作为第一个元素。
关于c++ - 在 C/C++ 中迭代 ndarray 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891546/