NumPy Swap Columns of Array
In data processing and machine learning, you often need to rearrange columns in a matrix or dataset.
NumPy makes this very easy using indexing and slicing techniques.
Swapping columns helps in:
- Reordering datasets
- Feature engineering
- Matrix transformations
- Data preprocessing
What Does Swapping Columns Mean?
Swapping columns means exchanging the positions of two or more columns in a 2D array.
Example:
Before:
[[1, 2, 3],
[4, 5, 6]]
After swapping column 0 and 2:
[[3, 2, 1],
[6, 5, 4]]
Why Swap Columns?
- Rearrange features in datasets
- Improve model input structure
- Data normalization steps
- Matrix manipulation
- Image processing
1. Basic Column Swap
import numpy as np
arr = np.array([
[1, 2, 3],
[4, 5, 6]
])
# Swap column 0 and column 2
arr[:, [0, 2]] = arr[:, [2, 0]]
print(arr)
Output
[[3 2 1]
[6 5 4]]
2. Swapping Adjacent Columns
arr = np.array([
[10, 20, 30, 40],
[50, 60, 70, 80]
])
# Swap column 1 and column 2
arr[:, [1, 2]] = arr[:, [2, 1]]
print(arr)
Output
[[10 30 20 40]
[50 70 60 80]]
3. Using Temporary Copy Method
arr = np.array([
[1, 2, 3],
[4, 5, 6]
])
temp = arr[:, 0].copy()
arr[:, 0] = arr[:, 2]
arr[:, 2] = temp
print(arr)
4. Swapping Multiple Columns
arr = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8]
])
# Rearranging columns
arr = arr[:, [3, 2, 1, 0]]
print(arr)
Output
[[4 3 2 1]
[8 7 6 5]]
5. Swap Columns in 3D Array
arr = np.array([
[[1, 2, 3],
[4, 5, 6]]
])
arr[:, :, [0, 2]] = arr[:, :, [2, 0]]
print(arr)
6. Swapping Columns in Real Dataset
data = np.array([
[100, 200, 300],
[400, 500, 600]
])
data[:, [0, 1]] = data[:, [1, 0]]
print(data)
7. Column Reordering (More Flexible)
arr = np.array([
[10, 20, 30],
[40, 50, 60]
])
# New order: column 2, 0, 1
arr = arr[:, [2, 0, 1]]
print(arr)
8. Real-World Example: Student Marks Table
students = np.array([
[90, 80, 70],
[85, 75, 65]
])
students[:, [0, 2]] = students[:, [2, 0]]
print(students)
9. Real-World Example: Sales Data
sales = np.array([
[100, 200, 300],
[400, 500, 600]
])
sales = sales[:, [1, 2, 0]]
print(sales)
Important Notes
- Column swapping works only on 2D arrays or higher
- Indexing must match array shape
- Data is modified in place unless copied
Common Techniques
| Method | Description |
|---|---|
| Fancy indexing | Swap using index list |
| Temporary variable | Classic swap method |
| Reordering | Change column order |
Advantages of Swapping Columns
- Easy data restructuring
- Useful in ML preprocessing
- Fast execution
- No loops required
- Clean and efficient code
Summary
NumPy allows easy swapping and rearranging of columns using indexing techniques. This is essential in data science, machine learning, and matrix manipulation tasks.
This functionality is part of NumPy and widely used in applications built with Python.
Conclusion
Swapping columns in NumPy is a powerful technique for reorganizing datasets efficiently. With simple indexing, you can transform and restructure arrays in seconds.


0 Comments