
- 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 - Concatenating Arrays
Concatenating NumPy Array
By concatenating a NumPy array, we mean to combine two or more arrays across different dimensions and axes to create a new array. This is helpful for combining arrays either vertically (along rows) or horizontally (along columns), depending on the need.
You can join arrays in Numpy using the concatenate() function available in the NumPy module.
The concatenate() Function
The concatenate() function in NumPy is used to concatenate (join together) arrays along a specified axis. It allows you to combine arrays either along rows or columns, depending on the axis parameter provided. Following is the syntax −
numpy.concatenate((a1, a2, ...), axis=0, out=None)
Where,
a1, a2, ... − These are the sequence of arrays to be joined. These arrays must have the same shape along all axes except the one specified by axis. Default is 0 (along rows). Use 1 for joining along columns.
axis − Specifies the axis along which the arrays will be joined.
out (optional) − This allows you to specify an output array where the result of concatenation will be stored.
Concatenating Arrays Along Rows
Concatenating arrays along rows in NumPy means stacking arrays vertically, placing one array on top of another to create a larger array. This is useful for combining datasets or expanding data vertically.
In NumPy, you can achieve this using the numpy.concatenate() function with "axis" argument set to "0".
Example
In the following example, we are concatenating two NumPy arrays "arr1" and "arr2" along rows using the numpy.concatenate() function −
import numpy as np arr1 = np.array([[1, 2, 3], [4, 5, 6]]) arr2 = np.array([[7, 8, 9], [10, 11, 12]]) # Concatenate along rows concatenated_arr = np.concatenate((arr1, arr2), axis=0) print("Concatenated Array along rows:",concatenated_arr)
Following is the output obtained −
Concatenated Array along rows: [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]]
Concatenating Arrays Along Columns
We can also concatenate arrays along columns in NumPy by stacking arrays horizontally, placing one array beside another to extend data horizontally. This is useful for combining datasets where each array represents columns of data that need to be joined.
In NumPy, you achieve this using the numpy.concatenate() function with the "axis" argument set to "1".
Example
In the example below, we are concatenating two NumPy arrays "arr1" and "arr2" along columns using the numpy.concatenate() function −
import numpy as np # Create two arrays arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6], [7, 8]]) # Concatenate along columns concatenated_arr = np.concatenate((arr1, arr2), axis=1) print("Concatenated Array along columns:") print(concatenated_arr)
This will produce the following result −
Concatenated Array along columns: [[1 2 5 6] [3 4 7 8]]
Concatenating Arrays with Mixed Dimensions
Concatenating arrays with mixed dimensions in NumPy involves combining arrays that initially have different shapes.
To achieve this, we use broadcasting techniques to adjust the shapes of the arrays so they are compatible for concatenation. This involves expanding the dimensions of the smaller arrays to match the larger arrays along the concatenation axis.
In NumPy, you can adjust the dimensions of arrays using functions such as np.reshape(), np.expand_dims(), and slicing.
Example: Concatenate 1D array with 2D array
Let us consider concatenating a 1D array with a 2D array. The 1D array will be expanded along the appropriate dimension to match the 2D array −
import numpy as np # Create a 1D array arr1 = np.array([1, 2, 3]) # Create a 2D array arr2 = np.array([[4, 5, 6], [7, 8, 9]]) # Expand dimensions of the 1D array to match the 2D array for concatenation along rows expanded_arr1 = np.expand_dims(arr1, axis=0) # Concatenate along rows (axis=0) concatenated_arr = np.concatenate((expanded_arr1, arr2), axis=0) print("Concatenated Array with Mixed Dimensions along rows:") print(concatenated_arr)
Following is the output of the above code −
Concatenated Array with Mixed Dimensions along rows: [[1 2 3] [4 5 6] [7 8 9]]
Example: Concatenate 2D array with 3D array
If you have arrays with more dimensions, you can similarly expand their dimensions to match each other. For example, concatenating a 2D array with a 3D array involves expanding the dimensions of the 2D array −
import numpy as np # Create a 2D array arr1 = np.array([[1, 2], [3, 4]]) # Create a 3D array arr2 = np.array([[[5, 6], [7, 8]], [[9, 10], [11, 12]]]) # Expand dimensions of the 2D array to match the 3D array for concatenation along the third dimension (axis=2) expanded_arr1 = np.expand_dims(arr1, axis=2) # Concatenate along the third dimension (axis=2) concatenated_arr = np.concatenate((expanded_arr1, arr2), axis=2) print("Concatenated Array with Mixed Dimensions along axis=2:") print(concatenated_arr)
The output obtained is as shown below −
Concatenated Array with Mixed Dimensions along axis=2: [[[ 1 5 6] [ 2 7 8]] [[ 3 9 10] [ 4 11 12]]]
Concatenating Arrays Along Specific Axes
You can concatenate arrays along axes other than "0" and "1" using the axis parameter of the concatenate() function. This parameter determines the dimension along which the arrays will be joined. By changing the value of axis, you can control whether the arrays are concatenated along rows, columns, or higher dimensions.
For arrays with more than two dimensions, you can specify higher axes for concatenation. For example, concatenating along the third axis (axis=2) involves combining arrays along their depth.
Example
In the following example, we are concatenating two 3D arrays along the third dimension −
import numpy as np # 3D arrays arr1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) arr2 = np.array([[[9, 10], [11, 12]], [[13, 14], [15, 16]]]) # Concatenate along the third dimension (axis=2) result = np.concatenate((arr1, arr2), axis=2) print("Concatenated along third dimension:") print(result)
After executing the above code, we get the following output −
Concatenated along third dimension: [[[ 1 2 9 10] [ 3 4 11 12]] [[ 5 6 13 14] [ 7 8 15 16]]]
Concatenating Arrays Using stack() Function
The NumPy stack() function can also be used to concatenate arrays along a new axis. Unlike numpy.concatenate(), which joins arrays along an existing axis, numpy.stack() adds an additional dimension, creating a new axis in the result. Following is the syntax −
numpy.stack(arrays, axis=0)
Where,
arrays − A sequence of arrays to be stacked. All arrays must have the same shape.
axis − The axis along which the arrays will be stacked. The default is 0.
Example
In the example below, we are stacking two 2D arrays along a new third axis (axis=2) using the NumPy stack() function −
import numpy as np # Example 2D arrays arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6], [7, 8]]) # Stack along a new third axis result = np.stack((arr1, arr2), axis=2) print("Stacked along a new axis:") print(result)
The result produced is as follows −
Stacked along a new axis: [[[1 5] [2 6]] [[3 7] [4 8]]]