简体   繁体   English

翻转或反转 numpy 阵列中的列

[英]Flip or reverse columns in numpy array

I want to flip the first and second values of arrays in an array.我想翻转数组中 arrays 的第一个和第二个值。 A naive solution is to loop through the array.一个天真的解决方案是遍历数组。 What is the right way of doing this?这样做的正确方法是什么?

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

flipped_contour = np.empty((0,2))
for point in contour:
    x_y_fipped = np.array([point[1], point[0]])
    flipped_contour = np.vstack((flipped_contour, x_y_fipped))

print(flipped_contour)

[[4. 1.]
[2. 3.]]

Use the aptly named np.flip : 使用恰当命名的np.flip

np.flip(contour, axis=1)

Or, 要么,

np.fliplr(contour)

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

您可以使用numpy 索引

contour[:, ::-1]

In addition to COLDSPEED's answer , if we only want to swap the first and second column only, not to flip the entire array: 除了COLDSPEED的答案外 ,如果我们只想只交换第一列和第二列,而不是翻转整个数组:

contour[:, :2] = contour[:, 1::-1]

Here contour[:, 1::-1] is the array formed by first two columns of the array contour , in the reverse order. 这里的contour[:, 1::-1]是由数组contour的前两列以相反的顺序形成的数组。 It then is assigned to the first two columns ( contour[:, :2] ). 然后将其分配给前两列( contour[:, :2] )。 Now the first two column are swapped. 现在,前两列已交换。

In general, to swap the i th and j th columns, do the following: 通常,要交换第i和第j列,请执行以下操作:

contour[:, [i, j]] = contour[:, [j, i]]

Here are two non-inplace ways of swapping the first two columns: 这是交换前两列的两种非就地方式:

>>> a = np.arange(15).reshape(3, 5)
>>> a[:, np.r_[1:-1:-1, 2:5]]
array([[ 1,  0,  2,  3,  4],
       [ 6,  5,  7,  8,  9],
       [11, 10, 12, 13, 14]])

or 要么

>>> np.c_[a[:, 1::-1], a[:, 2:]]
array([[ 1,  0,  2,  3,  4],
       [ 6,  5,  7,  8,  9],
       [11, 10, 12, 13, 14]])
>>> your_array[indices_to_flip] = np.flip(your_array[indices_to_flip], axis=1)

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

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