使用 C-API 反转 Numpy 数组中的轴
我正在使用 Python C-API 将一些 C++ 代码包装为 Python 包。 最后,我必须反转 numpy 数组中的轴,即执行
x = x[:, ::-1]
是否有某种方法可以使用 Numpy 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 about indexing.
Any ideas?
Thanks,
Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Python 中的索引只是调用对象的
__getitem__()
方法的语法糖(即x[:, ::-1]
相当于x.__getitem__ ((slice(None), slice(None, None, -1)))
),您只需构造所需的切片对象,将它们以正确的顺序存储在元组中,然后调用该对象的以元组为参数的 __getitem__() 方法。您需要查看以下链接:
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
不过,如果您还没有阅读过如何使用 C API,我建议您首先阅读如何使用 C API,因为如果您只习惯常规的 Python,这可能会有点令人困惑。例如,必须使用
Py_DECREF()
或Py_XDECREF()
宏显式减少代码中创建的任何引用的引用计数。 http://docs.python.org/c-api/refcounting.htmlAs indexing in Python is just syntactic sugar for calling an object's
__getitem__()
method (i.e.x[:, ::-1]
is equivalent tox.__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()
orPy_XDECREF()
macros. http://docs.python.org/c-api/refcounting.html