Reversing axis in Numpy array using C-API
I am using the Python C-API to wrap some C++ code as a Python package. In the end, I have to reverse an axis in a numpy array, i.e. doing
x = x[:, ::-1]
Is there some way of doing this using the Numpy C-API? I know there are routines for transposing and swaping axes but I haven't found much 开发者_如何学JAVAabout indexing. Any ideas? Thanks, Andy
As indexing in Python is just syntactic sugar for calling an object's __getitem__()
method (i.e. x[:, ::-1]
is equivalent to x.__getitem__((slice(None), slice(None, None, -1)))
), you just have to construct the required slice objects, store them in the correct order in a tuple, and then call the object's __getitem__()
method with the tuple as the argument.
You'll want to check out the following links:
http://docs.python.org/c-api/slice.html#PySlice_New
http://docs.python.org/c-api/tuple.html#PyTuple_Pack
http://docs.python.org/c-api/object.html#PyObject_GetItem
I'd recommend reading up on how to use the C API in the first place if you haven't already, though, because it can be kind of confusing if you're only used to regular Python. For instance, having to explicitly decrement the reference count for any references created in your code using the Py_DECREF()
or Py_XDECREF()
macros. http://docs.python.org/c-api/refcounting.html
精彩评论