Reputation: 6826
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.]]
Upvotes: 10
Views: 22579
Reputation: 61
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]])
Upvotes: 0
Reputation: 1
>>> your_array[indices_to_flip] = np.flip(your_array[indices_to_flip], axis=1)
Upvotes: 0
Reputation: 1352
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]]
Upvotes: 7
Reputation: 53029
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]])
Upvotes: 3
Reputation: 402613
Use the aptly named np.flip
:
np.flip(contour, axis=1)
Or,
np.fliplr(contour)
array([[4, 1],
[2, 3]])
Upvotes: 17