
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
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]]]