简体   繁体   English

numpy反向多维数组

[英]numpy reverse multidimensional array

What is the simplest way in numpy to reverse the most inner values of an array like this: numpy中最简单的方法是反转数组的最内部值,如下所示:

array([[[1, 1, 1, 2],
    [2, 2, 2, 3],
    [3, 3, 3, 4]],

   [[1, 1, 1, 2],
    [2, 2, 2, 3],
    [3, 3, 3, 4]]])

so that I get the following result: 这样我得到以下结果:

array([[[2, 1, 1, 1],
    [3, 2, 2, 2],
    [4, 3, 3, 3]],

   [[2, 1, 1, 1],
    [3, 2, 2, 2],
    [4, 3, 3, 3]]])

Thank you very much! 非常感谢你!

How about: 怎么样:

import numpy as np
a = np.array([[[10, 1, 1, 2],
               [2, 2, 2, 3],
               [3, 3, 3, 4]],
              [[1, 1, 1, 2],
               [2, 2, 2, 3],
               [3, 3, 3, 4]]])

and the reverse along the last dimension is: 而最后一个维度的反面是:

b = a[:,:,::-1]

or 要么

b = a[...,::-1]

although I like the later less since the first two dimensions are implicit and it is more difficult to see what is going on. 虽然我喜欢后者较少,因为前两个维度是隐含的,并且更难以看到发生了什么。

For each of the inner array you can use fliplr . 对于每个内部数组,您可以使用fliplr It flips the entries in each row in the left/right direction. 它会向左/右方向翻转每行中的条目。 Columns are preserved, but appear in a different order than before. 列保留,但显示的顺序与以前不同。

Sample usage: 样品用法:

import numpy as np
initial_array = np.array([[[1, 1, 1, 2],
                          [2, 2, 2, 3],
                          [3, 3, 3, 4]],
                         [[1, 1, 1, 2],
                          [2, 2, 2, 3],
                          [3, 3, 3, 4]]])
index=0
initial_shape = initial_array.shape
reversed=np.empty(shape=initial_shape)
for inner_array in initial_array:
    reversed[index] = np.fliplr(inner_array)
    index += 1

printing reversed 印刷逆转

Output: 输出:

array([[[2, 1, 1, 1],
        [3, 2, 2, 2],
        [4, 3, 3, 3]],
       [[2, 1, 1, 1],
        [3, 2, 2, 2],
        [4, 3, 3, 3]]])

Make sure your input array for fliplr function must be at least 2-D. 确保fliplr函数的输入数组必须至少为2-D。

Moreover if you want to flip array in the up/down direction. 此外,如果你想在上/下方向翻转阵列。 You can also use flipud 你也可以使用flipud

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

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