In this topic, we discuss how to easily merge 3 numpy matrix in numpy in Python programming. Let’s explore how to merge 3 numpy matrix in numpy in python program.
Merge 3 NumPy Matrix
Table of contents :
- Introduction
- Program to Merge 3 numpy matrix
- Output
- Conclusion
Introduction to Merging NumPy Matrices :
NumPy is a powerful library for numerical computations in Python. One of its features is the ability to easily merge arrays (or matrices). Here’s how you can merge three matrices:
Importing the NumPy Library
Creating the Matrices
Concatenating the Matrices Vertically
Concatenating the Matrices Horizontally
Concatenating the Matrices Along a Specific Axis
Program to Merge 3 NumPy Matrix :
import numpy as np
# Create sample matrices
matrix1 = np.array([[1, 2, 3,],[4, 5, 6]])
matrix2 = np.array([[7, 8, 9],[10, 11, 12]])
matrix3 = np.array([[13, 14, 15],[16, 17, 18]])
# Vertical concatenation
vertical_concat = np.vstack((matrix1, matrix2, matrix3))
print(“Vertical Concatenation:\n”, vertical_concat)
# Horizontal concatenation
horizontal_concat = np.hstack((matrix1, matrix2, matrix3))
print(“Horizontal Concatenation:\n”, horizontal_concat)
# Concatenation along a new axis
new_axis_concat = np.stack((matrix1, matrix2, matrix3), axis=0)
print(“New Axis Concatenation:\n”, new_axis_concat)
Output :
Vertical Concatenation:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]
[13 14 15]
[16 17 18]]
Horizontal Concatenation:
[[ 1 2 3 7 8 9 13 14 15]
[ 4 5 6 10 11 12 16 17 18]]
New Axis Concatenation:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]
[[13 14 15]
[16 17 18]]]
=== Code Execution Successful ===
Conclusion:
Merging three NumPy matrices can be easily achieved using ‘np.vstack’ for vertical stacking, ‘np.hstack’ for horizontal stacking, and ‘np.stack’ for adding a new axis, enabling flexible data manipulation