![]() |
VOOZH | about |
Swapping columns of a NumPy array means exchanging the positions of two specified columns across all rows. For example, if you have a 3x3 array with values like [[0, 1, 2], [3, 4, 5], [6, 7, 9]] and you swap column 0 with column 2, the array becomes [[2, 1, 0], [5, 4, 3], [9, 7, 6]]. Let’s explore different ways to do this efficiently using NumPy.
This is the simplest method, where we use slicing to specify the column indices to swap like a[:, [0, 2]] = a[:, [2, 0]]. It swaps the columns in-place, making it fast and ideal for quick operations on the original array.
Original array: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] After swapping: [[ 2 1 0] [ 5 4 3] [ 8 7 6] [11 10 9]]
Explanation: a[:, [0, 2]] = a[:, [2, 0]] selects all rows and swaps columns 0 and 2. It replaces column 0 with column 2 and vice versa, modifying the original array in-place without creating a new one.
This method uses list comprehension to create a new column order, offering flexibility for dynamic or reusable functions. Define i and j, build the new index list and reindex the array. It requires slightly more code but provides greater control.
Original array: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] [[ 2 1 0] [ 5 4 3] [ 8 7 6] [11 10 9]]
Explanation: List comprehension swaps columns 0 and 2 by generating a new column order. It selects all rows and returns a new array with the specified columns swapped, leaving the original array unchanged.
np.take() lets you reorder or extract elements along a specific axis. For column swapping, create a new column order and use np.take() to apply it. It returns a new array, keeping the original unchanged.
Original array: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] After swapping: [[ 2 1 0] [ 5 4 3] [ 8 7 6] [11 10 9]]
Explanation: np.take(a, col_order, axis=1) swaps columns 0 and 2 by applying the new column order col_order to all rows using np.take(). This returns a new array with the specified columns swapped, while keeping the original array unchanged.
To preserve the original data, use np.copy() and swap columns on the copy using direct indexing. It’s a safe and simple method that leaves the original array untouched.
Original array: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] After swapping: [[ 2 1 0] [ 5 4 3] [ 8 7 6] [11 10 9]]
Explanation: a.copy() creates a copy to preserve the original array. The line res[:, [0, 2]] = res[:, [2, 0]] swaps columns 0 and 2 in the copy, returning a modified array while leaving the original unchanged.