Search code examples
pythonnumpyswapnumpy-ndarraynotation

Notation of swapping rows on a numpy array in Python


Lets say we have a numpy array:

A = np.array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
          [10, 11, 12]])

    

Can anyone explain why this line is used to swap two rows(in this occasion the 1st with the 4th)?

'A[[0, 3]] = A [[3, 0]]'

Solution

  • You are updating the positions of two subarrays simultaneously.

    However, doing:

    A[0] = A[3]
    A[3] = A[0]
    

    would not work because the subarray A[0] has already been updated, so you need to do it simultaneously with:

    A[[0, 3]] = A [[3, 0]]
    A
    array([[10, 11, 12],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [ 1,  2,  3]])