Search code examples
pythonarraysnumpyswap

swap two elements in 2d array


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

Solution

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