简体   繁体   English

如何翻转 numpy 阵列的一半

[英]How to flip half of a numpy array

I have a numpy array:我有一个 numpy 阵列:

arr=np.array([[1., 2., 0.],
               [2., 4., 1.],
               [1., 3., 2.],
               [-1., -2., 4.],
               [-1., -2., 5.],
               [1., 2., 6.]])

I want to flip the second half of this array upward.我想向上翻转这个数组的后半部分。 I mean I want to have:我的意思是我想要:

flipped_arr=np.array([[-1., -2., 4.],
                      [-1., -2., 5.],
                      [1., 2., 6.],
                      [1., 2., 0.],
                      [2., 4., 1.],
                      [1., 3., 2.]])

When I try this code:当我尝试这段代码时:

fliped_arr=np.flip(arr, 0)

It gives me:它给了我:

fliped_arr= array([[1., 2., 6.],
                   [-1., -2., 5.],
                   [-1., -2., 4.],
                   [1., 3., 2.],
                   [2., 4., 1.],
                   [1., 2., 0.]])

In advance, I do appreciate any help.在此之前,我非常感谢任何帮助。

You can simply concatenate rows below the n th row (included) with np.r_ for instance, with row index n of your choice, at the top and the other ones at the bottom:您可以简单地将第n行(包括)下方的行与np.r_ 连接起来,例如,您选择的行索引n位于顶部,其他行位于底部:

import numpy as np
n = 3

arr_flip_n = np.r_[arr[n:],arr[:n]]

>>> array([[-1., -2.,  4.],
           [-1., -2.,  5.],
           [ 1.,  2.,  6.],
           [ 1.,  2.,  0.],
           [ 2.,  4.,  1.],
           [ 1.,  3.,  2.]])

you can do this by slicing the array using the midpoint:您可以通过使用中点对数组进行切片来做到这一点:

ans = np.vstack((arr[int(arr.shape[0]/2):], arr[:int(arr.shape[0]/2)]))

to break this down a little:把它分解一下:

find the midpoint of arr, by finding its shape, the first index of which is the number of rows, dividing by two and converting to an integer:找到 arr 的中点,通过找到它的形状,第一个索引是行数,除以 2 并转换为 integer:

midpoint = int(arr.shape[0]/2)

the two halves of the array can then be sliced like so:然后可以像这样切片数组的两半:

a = arr[:midpoint]
b = arr[midpoint:]

then stack them back together using np.vstack :然后使用np.vstack将它们堆叠在一起:

ans = np.vstack((a, b))

(note vstack takes a single argument, which is a tuple containing a and b: (a, b) ) (注意 vstack 接受一个参数,它是一个包含 a 和 b 的元组: (a, b)

You can do this with array slicing and vstack -您可以使用数组切片和 vstack 来做到这一点 -

arr=np.array([[1., 2., 0.],
               [2., 4., 1.],
               [1., 3., 2.],
               [-1., -2., 4.],
               [-1., -2., 5.],
               [1., 2., 6.]])

mid = arr.shape[0]//2  
np.vstack([arr[mid:],arr[:mid]])
array([[-1., -2.,  4.],
       [-1., -2.,  5.],
       [ 1.,  2.,  6.],
       [ 1.,  2.,  0.],
       [ 2.,  4.,  1.],
       [ 1.,  3.,  2.]])

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

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