How to zip two 2D NumPy arrays?

Given two 2D NumPy arrays, we have to add zip them.
By Pranit Sharma Last updated : December 25, 2023

Problem statement

Suppose that we are given two 2D numpy arrays and we need to zip these arrays so that we can get the values of both arrays together along with the corresponding map value.

For example, if we have [[1,2,3],[4,5,6]] and [[1,2,3],[4,5,6]] as two numpy arrays and we need to zip them together.

Zip two 2D NumPy arrays

To zip two 2D NumPy arrays, we can use the numpy.dstack() method. This method stack arrays in sequence depth-wise. This can be considered as concatenation along the third axis after 2-D arrays of shape (M, N) have been reshaped to (M, N,1).

Below is the syntax of numpy.dstack() method:

numpy.dstack(tup)

Let us understand with the help of an example,

Python program to zip two 2D NumPy arrays

# Import numpy
import numpy as np

# Creating two numpy arrays
arr = np.array([[0, 1, 2, 3],[4, 5, 6, 7]])
arr1 = np.array([[0, 1, 2, 3],[4, 5, 6, 7]])

# Display Original arrays
print("Original array:\n",arr,"\n")
print("Original array 2:\n",arr1,"\n")

# Applying dstack on arrays
res = np.dstack((arr,arr1))

# Display result
print("Result:\n",res,"\n")

Output

The output of the above program is:

Example: How to zip two 2D NumPy arrays?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.