简体   繁体   English

翻转任意维度的 numpy 数组

[英]Flip numpy array of arbitrary dimension

I would like to construct a helper function that flips a multidimensional numpy array of arbitrary dimension, in all dimensions.我想构建一个辅助函数,它可以在所有维度上翻转任意维度的多维 numpy 数组。 Surprisingly, I haven't found anything online about this.令人惊讶的是,我在网上没有找到任何关于此的信息。

We could do something ugly like this:我们可以做一些像这样丑陋的事情:

d = len(X.shape)
if d == 1:
    reversed_X = X[::-1]
elif d == 2:
    reversed_X = X[::-1, ::-1]
elif d == 3:
    reversed_X = X[::-1, ::-1, ::-1]
elif d == 4:
    reversed_X = X[::-1, ::-1, ::-1, ::-1]  
# ...etc

But there has to be a better way.但必须有更好的方法。

I tried building a list of slice objects and using them as follows:我尝试构建切片对象列表并按如下方式使用它们:

X[[slice(s,-1,-1) for s in X.shape]]

but this returned an empty array (!).但这返回了一个空数组(!)。 Changing the endpoint of the slices, as in:更改切片的端点,如下所示:

X[[slice(s,0,-1) for s in X.shape]]

almost works, but it misses the last index in each dimension, making the "reversed" array slightly smaller than the original.几乎可以工作,但它错过了每个维度的最后一个索引,使“反向”数组比原始数组略小。

Figured out the answer to my own question almost immediately after I posted it.发布后几乎立即找出了我自己问题的答案。 Posting here for future people.在这里发布给未来的人。

Slice objects can't be told to stop at -1 for some reason, even when striding backwards.出于某种原因,不能告诉切片对象在 -1 处停止,即使向后大步走也是如此。 But luckily you can stop at 'None', which saturates the array backwards.但幸运的是,您可以停在“无”处,这会使数组向后饱和。 Applying this to the code in the original question works:将此应用于原始问题中的代码有效:

reversed_X = X[tuple([slice(None, None, -1) for _ in range(X.ndim)])]

Example:示例:

In: X = np.reshape(np.arange(2*3), (2,3))
In: X
Out: 
array([[0, 1, 2],
       [3, 4, 5]])
In: X[tuple([slice(None, None, -1) for _ in range(X.ndim)])]
Out: 
array([[5, 4, 3],
       [2, 1, 0]])

numpy.flip(m, axis) (New in numpy version 1.12.0.) numpy.flip(m, axis) (numpy 1.12.0 版中的新功能。)

So this might work:所以这可能有效:

for k in range(X.ndim):
    X = np.flip(X, k)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM