簡體   English   中英

在C / C ++中遍歷ndarray列

[英]Iterating over ndarray columns in C/C++

如何獲得類似於以下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似乎確實令人費解,並且該文檔也不是非常適合初學者,因此也希望引用任何更簡單的指南。

您應該通過PyArray_XXX函數(例如PyArray_NDIM)訪問PyArrayObject的內部結構。 要獲取序列的內容,請使用帶有元組鍵的PyObject_GetItem ,在用例中,元組將以PySliceObject作為第一個元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM