[英]How to use numpy to flip this array?
Suppose I have an array like this:假设我有一个这样的数组:
a = array([[[ 29, 29, 27],
[ 36, 38, 40],
[ 86, 88, 89]],
[[200, 200, 198],
[199, 199, 197]
[194, 194, 194]]])
and I want to flip the 3rd element from left to right in the list-of-lists so it will become like this:我想在列表列表中从左到右翻转第三个元素,所以它会变成这样:
b = array([[[ 29, 29, 89], # 27 became 89
[ 36, 38, 40],
[ 86, 88, 27]], # 89 became 27
[[200, 200, 194], # 198 became 194
[199, 199, 197],
[194, 194, 198]]]) # 194 became 198
I looked up the NumPy manual but I still cannot figure out a solution.我查阅了 NumPy 手册,但仍然找不到解决方案。
.flip
and .fliplr
look suitable in this case, but how do I use them? .flip
和.fliplr
在这种情况下看起来很合适,但我该如何使用它们?
Index the array to select the sub-array, using:索引数组以选择子数组,使用:
> a[:,:,-1]
array([[198, 197, 194],
[ 27, 40, 89]])
This selects the last element along the 3rd dimension of a
.这将选择沿的第三尺寸的最后一个元素
a
。 The sub-array is of shape (2,3)
.子数组的形状为
(2,3)
。 Then reverse the selection using:然后使用以下方法反转选择:
a[:,:,-1][:,::-1]
The second slice, [:,::-1]
, takes everything along the first dimension as-is ( [:]
), and all of the elements along the second dimension, but reversed ( [::-1]
).第二个切片
[:,::-1]
将沿第一个维度的所有内容 ( [:]
) 以及沿第二个维度的所有元素颠倒 ( [::-1]
)。 The slice syntax is basically saying start at the first element, go the last element ( [:]
), but do it in the reverse order ( [::-1]
).切片语法基本上是说从第一个元素开始,到最后一个元素 (
[:]
),但以相反的顺序 ( [::-1]
) 执行。 You could pseudo-code write it as [start here : end here : use this step size]
.你可以用伪代码把它写成
[start here : end here : use this step size]
。 The the -1
tells it walk backwards. -1
告诉它向后走。
And assign it to the first slice of the original array.并将其分配给原始数组的第一个切片。 This updates/overwrites the original value of
a
此更新/覆盖的原始值
a
a[:,:,-1] = a[:,:,-1][:,::-1]
> a
array([[[ 29, 29, 89],
[ 36, 38, 40],
[ 86, 88, 27]],
[[200, 200, 194],
[199, 199, 197],
[194, 194, 198]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.