
- 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 - Insert Axes to an Array
Insert Axes to an Array in NumPy
Inserting axes into a NumPy array refers to adding new dimensions to the existing array. This is particularly useful when you need to align data for broadcasting, reshape arrays for specific operations, or add new dimensions to facilitate operations such as stacking or concatenation.
The primary function used for this purpose is np.expand_dims(), which adds a new axis at a specified position.
Insert Axes Using expand_dims() Function
The np.expand_dims() function in NumPy is used to insert a new axis (dimension) into an existing array, thereby increasing its dimensionality. Following is the syntax −
numpy.expand_dims(a, axis)
Where,
- a: It is the input array.
- axis: It is the position in the dimensions where the new axis is to be inserted.
Example
In the following example, we start with creating a 1D array. Using np.expand_dims() function, we add a new axis at position 1, transforming the array into a 2D column vector −
import numpy as np # Creating a 1D NumPy array arr = np.array([1, 2, 3, 4]) # Adding a new axis to create a 2D column vector expanded_arr = np.expand_dims(arr, axis=1) print("Original Array:\n", arr) print("Array with New Axis:\n", expanded_arr)
Following is the output obtained −
Original Array: [1 2 3 4] Array with New Axis: [[1] [2] [3] [4]]
Insert Axes to Create Higher-dimensional Arrays
Inserting axes to create higher-dimensional arrays means adding new dimensions to an existing array, which changes its shape. This process allows you to expand the array from, for example, 1D to 2D or from 2D to 3D.
This is useful for operations like broadcasting or reshaping data to fit specific requirements.
Example
In this example, we are expanding a 1D NumPy array to a 3D array by adding two new axes using the np.expand_dims() function −
import numpy as np # Creating a 1D NumPy array arr = np.array([1, 2, 3]) # Adding two new axes to create a 3D array expanded_arr = np.expand_dims(arr, axis=(0, 2)) print("Original Array:\n", arr) print("3D Array with New Axes:\n", expanded_arr) print("Shape of 3D Array:", expanded_arr.shape)
This will produce the following result −
Original Array: [1 2 3] 3D Array with New Axes: [[[1] [2] [3]]] Shape of 3D Array: (1, 3, 1)
Insert Axes Using "None" or "np.newaxis" Indexing
An alternative way to insert axes is by using None or np.newaxis indexing. This approach is generally used for its simplicity and readability in code.
By indexing with "None" or "np.newaxis", you can expand a 1D array to 2D or 3D, or adjust the shape as needed.
Example
In the example below, we are transforming a 1D NumPy array into a 2D row vector by adding a new axis with np.newaxis indexing −
import numpy as np # Creating a 1D NumPy array arr = np.array([1, 2, 3, 4]) # Adding a new axis to create a 2D row vector row_vector = arr[:, np.newaxis] print("Original Array:\n", arr) print("2D Row Vector:\n", row_vector)
Following is the output of the above code −
Original Array: [1 2 3 4] 2D Row Vector: [[1] [2] [3] [4]]
Combining Multiple Arrays with Inserted Axes
Combining multiple arrays with inserted axes involves adding new dimensions to each array so they align properly for concatenation or stacking.
By inserting axes, you ensure that arrays of different shapes can be joined together. This technique allows for flexible data manipulation and performing various operations.
Example
In the following example, we are adding a new axis to each 1D array to convert them into 2D row vectors. We then concatenate these row vectors along axis 0, resulting in a 2D array where each original array is now a separate row −
import numpy as np # Creating two 1D arrays arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) # Adding new axes to create 2D row vectors arr1_expanded = arr1[np.newaxis, :] arr2_expanded = arr2[np.newaxis, :] # Concatenating the row vectors along axis 0 combined_arr = np.concatenate([arr1_expanded, arr2_expanded], axis=0) print("Array 1 with New Axis:\n", arr1_expanded) print("Array 2 with New Axis:\n", arr2_expanded) print("Combined Array:\n", combined_arr)
The output obtained is as shown below −
Array 1 with New Axis: [[1 2 3]] Array 2 with New Axis: [[4 5 6]] Combined Array: [[1 2 3] [4 5 6]]