NumPy - Swap Columns of Array



Swapping Columns of Array in NumPy

Swapping columns in a NumPy array refers to exchanging the positions of two or more columns within the array. This operation can be performed on both 1-dimensional and multi-dimensional arrays.

The primary approach for swapping columns involves slicing and indexing, which allows you to access and rearrange the columns as needed.

Swapping Columns Using Indexing

Swapping columns in a NumPy array using indexing is a technique where you change the order of columns within a 2D array by selecting and reassigning specific columns based on their indices.

Example

In the following example, we are swapping the "first" and "last" columns of a 2D NumPy array using indexing −

import numpy as np

# Creating a 2D NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Swapping the first and last columns
arr[:, [0, 2]] = arr[:, [2, 0]]

print("Array after swapping columns:")
print(arr)

Following is the output obtained −

Array after swapping columns:
[[3 2 1]
 [6 5 4]
 [9 8 7]]

Swapping Multiple Columns

Swapping multiple columns in a NumPy array involves changing the order of more than two columns simultaneously. The process uses advanced indexing to specify which columns to swap and their new positions.

Example

In this example, we are swapping three columns of a 2D array such that the first column moves to the third position, the second column moves to the first position, and the third column moves to the second position −

import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

# Swap columns in the order: 1st to 3rd, 2nd to 1st, 3rd to 2nd
arr[:, [0, 1, 2]] = arr[:, [1, 2, 0]]

print("Array after swapping columns:")
print(arr)

This will produce the following result −

Array after swapping columns:
[[2 3 1]
 [5 6 4]
 [8 9 7]]

Swapping Columns in a 3D Array

Swapping columns in a 3D array in NumPy involves rearranging the elements along one of the axes of the array, usually the second axis (axis 1), which corresponds to the columns when dealing with a slice of the 3D array.

Example

In the example below, we swap the first and last columns along the second axis (axis 2) of the 3D array. The array is sliced along the first two axes, and the third axis is indexed to perform the column swap −

import numpy as np

# Creating a 3D NumPy array
arr = np.array([[[1, 2, 3], [4, 5, 6]], 
                [[7, 8, 9], [10, 11, 12]]])

# Swapping the first and last columns along the second axis
arr[:, :, [0, 2]] = arr[:, :, [2, 0]]

print("3D array after swapping columns:")
print(arr)

Following is the output of the above code −

3D array after swapping columns:
[[[ 3  2  1]
 [ 6  5  4]]
[[ 9  8  7]
 [12 11 10]]]

Swapping Non-Adjacent Columns

Swapping non-adjacent columns in a NumPy array refers to rearranging columns that are not directly next to each other.

This operation can be performed in both 2D and 3D arrays, and it uses advanced indexing techniques to specify which columns to swap.

Example

In the following example, we are swapping non-adjacent columns i.e. the first and third columns in a 2D NumPy array using advanced indexing −

import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3, 4],
                [5, 6, 7, 8],
                [9, 10, 11, 12]])

# Swap the first (index 0) and third (index 2) columns
arr[:, [0, 2]] = arr[:, [2, 0]]

print("Array after swapping non-adjacent columns:")
print(arr)

The output obtained is as shown below −

Array after swapping non-adjacent columns:
[[ 3  2  1  4]
 [ 7  6  5  8]
 [11 10  9 12]]

Swapping Columns in Structured Arrays

To swap columns in structured arrays, we need to rearrange fields within the structured array while preserving the integrity of each record.

Structured arrays in NumPy allow you to define arrays with heterogeneous data types, and each element of the array can contain multiple fields.

Example

In this example, we are swapping the columns 'A' and 'C' in a structured NumPy array using field-based indexing −

import numpy as np

# Create a structured array
dtype = [('A', 'i4'), ('B', 'i4'), ('C', 'i4')]
arr = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=dtype)

# Swap columns 'A' and 'C'
arr[['A', 'C']] = arr[['C', 'A']]

print("Structured array after swapping columns 'A' and 'C':")
print(arr)

After executing the above code, we get the following output −

Structured array after swapping columns 'A' and 'C':
[(3, 2, 1) (6, 5, 4) (9, 8, 7)]

Swap Columns Using swapaxes() Function

We can use the np.swapaxes() function for more complex operations involving multiple axes. This function allows you to swap two specified axes of an array, which can be particularly useful in higher-dimensional arrays.

Following is the syntax −

numpy.swapaxes(a, axis1, axis2)

Where,

  • a: The input array whose axes are to be swapped.
  • axis1: The first axis to be swapped.
  • axis2: The second axis to be swapped.

Example

In the following example, we are using the np.swapaxes() function to swap the second and third axes, effectively reordering the columns in the 3D array −

import numpy as np

# Creating a 3D NumPy array
arr = np.array([[[1, 2, 3], [4, 5, 6]], 
                [[7, 8, 9], [10, 11, 12]]])

# Swapping axes 1 and 2
arr_swapped = np.swapaxes(arr, 1, 2)

print("3D array after swapping axes:")
print(arr_swapped)

The result produced is as follows −

3D array after swapping axes:
[[[ 1  4]
  [ 2  5]
  [ 3  6]]

 [[ 7 10]
  [ 8 11]
  [ 9 12]]]
Advertisements