简体   繁体   中英

Flip or reverse columns in numpy array

I want to flip the first and second values of arrays in an array. 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(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:

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. It then is assigned to the first two columns ( contour[:, :2] ). Now the first two column are swapped.

In general, to swap the i th and j th columns, do the following:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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