繁体   English   中英

翻转或反转 numpy 阵列中的列

[英]Flip or reverse columns in numpy array

我想翻转数组中 arrays 的第一个和第二个值。 一个天真的解决方案是遍历数组。 这样做的正确方法是什么?

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.]]

使用恰当命名的np.flip

np.flip(contour, axis=1)

要么,

np.fliplr(contour)

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

您可以使用numpy 索引

contour[:, ::-1]

除了COLDSPEED的答案外 ,如果我们只想只交换第一列和第二列,而不是翻转整个数组:

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

这里的contour[:, 1::-1]是由数组contour的前两列以相反的顺序形成的数组。 然后将其分配给前两列( contour[:, :2] )。 现在,前两列已交换。

通常,要交换第i和第j列,请执行以下操作:

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

这是交换前两列的两种非就地方式:

>>> 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]])

要么

>>> 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