Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.]]
like image 369
waspinator Avatar asked Mar 28 '18 23:03

waspinator


People also ask

How do I flip columns and rows in NumPy?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.

How do you reverse the order of elements in a NumPy array?

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

How do I flip a NumPy array horizontally?

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

How do you reverse the order of elements along columns?

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.


2 Answers

Use the aptly named np.flip:

np.flip(contour, axis=1)

Or,

np.fliplr(contour)

array([[4, 1],
       [2, 3]])
like image 115
cs95 Avatar answered Oct 06 '22 04:10

cs95


You can use numpy indexing:

contour[:, ::-1]
like image 31
jpp Avatar answered Oct 06 '22 06:10

jpp