10

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

6 Answers 6

18

Use the aptly named np.flip:

np.flip(contour, axis=1)

Or,

np.fliplr(contour)

array([[4, 1],
       [2, 3]])
Sign up to request clarification or add additional context in comments.

Comments

9

You can use numpy indexing:

contour[:, ::-1]

Comments

7

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 ith and jth columns, do the following:

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

1 Comment

That should be contour[:, :2] = contour[:, 1::-1], shouldn't it?
3

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

Comments

0
>>> your_array[indices_to_flip] = np.flip(your_array[indices_to_flip], axis=1)

Comments

0

Another way would be using permutation matrices

import numpy as np

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

P = np.array([[0, 1],
         [1, 0]])#permutation matrix that will 
                 #swap column 1 with column 2 if right multiplied

contour = contour @ P
print(contour)

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.