在3d numpy数组中交换元素

时间:2017-04-07 02:32:03

标签: arrays numpy python-3.4

给定3d numpy数组如何交换每个像素的第一个和最后一个元素'

例如:

a = [[[15  3 61]
    [56 27 22]
    [48 32 29]
    [38 21 50]
    [28 54 37]]

    [[47 27 35]
    [52 34 12]
    [18 56 48]
    [ 8 34  1]
    [37 27 38]]]

我希望数组为:

a = [[[61  3 15]
    [22 27 56]
    [29 32 48]
    [50 21 38]
    [37 54 28]]

等等

有没有办法不使用循环?

1 个答案:

答案 0 :(得分:1)

您可以按a[..., ::-1]

沿第三轴反转数组
a = np.array([[[15,  3, 61],
    [56, 27, 22],
    [48, 32, 29],
    [38, 21, 50],
    [28, 54, 37]],
    [[47, 27, 35],
    [52, 34, 12],
    [18, 56, 48],
    [ 8, 34,  1],
    [37, 27, 38]]])

a[..., ::-1]
#array([[[61,  3, 15],
#        [22, 27, 56],
#        [29, 32, 48],
#        [50, 21, 38],
#        [37, 54, 28]],

#       [[35, 27, 47],
#        [12, 34, 52],
#        [48, 56, 18],
#        [ 1, 34,  8],
#        [38, 27, 37]]])