Transposing and Swapping Axes in NumPy

NumPy provides functions to transpose and swap axes of arrays, enabling efficient reorganization of data. The main functions used for these operations are:

  • transpose() - Transposes the dimensions of an array.
  • swapaxes() - Swaps two specified axes of an array.

1. Transposing an Array (transpose)

The transpose() function flips the dimensions of an array, converting rows into columns and vice versa.

    import numpy as np
    
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    transposed_arr = np.transpose(arr)
    print(transposed_arr)
        

Output:

    [[1 4]
     [2 5]
     [3 6]]
        

2. Swapping Axes (swapaxes)

The swapaxes() function swaps two axes of an array.

    arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
    swapped_arr = np.swapaxes(arr, 0, 2)
    print(swapped_arr)
        

Output:

    [[[1 5]
      [3 7]]
    
     [[2 6]
      [4 8]]]
        

Conclusion

Transposing and swapping axes in NumPy are powerful techniques for reshaping data. The transpose() function changes the order of dimensions, while swapaxes() allows for specific axis swaps to restructure arrays as needed.





Advertisement