swap two elements in 2d array

Viewed 155

I have an array of the shape (10296, 6). I want to swap the two last elements in the subarray.

a = [[1, 2, 3, 4, 5, 6][1, 2, 3, 4, 5, 6]...

So that 5 and 6 of each array is swapped into:

a = [[1, 2, 3, 4, 6, 5][1, 2, 3, 4, 6, 5]...
1 Answers

Try advanced slicing in numpy. Read more here -

import numpy as np

a = np.array([[1, 2, 3, 4, 5, 6],
              [1, 2, 3, 4, 5, 6]])

a[:,[4, 5]] = a[:,[5, 4]]
array([[1, 2, 3, 4, 6, 5],
       [1, 2, 3, 4, 6, 5]])
Related