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.]]
To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.
Using fliplr() function The numpy. flipr() function always accepts a given array as a parameter and returns the same array and flip in the left-right direction. It reverses the order of elements on the given axis as 1 (left/right).
Flip an array vertically (axis=0). Flip an array horizontally (axis=1). flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m).
B = flip( A , dim ) reverses the order of the elements in A along dimension dim . For example, if A is a matrix, then flip(A,1) reverses the elements in each column, and flip(A,2) reverses the elements in each row.
Use the aptly named np.flip
:
np.flip(contour, axis=1)
Or,
np.fliplr(contour)
array([[4, 1],
[2, 3]])
You can use numpy
indexing:
contour[:, ::-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With