NumPy: Merge three given NumPy arrays of same shape
Merge three arrays of the same shape.
Write a NumPy program to merge three given NumPy arrays of same shape.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating three random arrays of shape (25, 25, 1)
arr1 = np.random.random(size=(25, 25, 1))
arr2 = np.random.random(size=(25, 25, 1))
arr3 = np.random.random(size=(25, 25, 1))
# Printing the original arrays
print("Original arrays:")
print(arr1)
print(arr2)
print(arr3)
# Concatenating the arrays along the last axis (-1) using np.concatenate
result = np.concatenate((arr1, arr2, arr3), axis=-1)
# Printing the concatenated array
print("\nAfter concatenate:")
print(result)
Sample Output:
Original arrays: [[[2.42789481e-01] [4.92252795e-01] [9.33448807e-01] [7.25450297e-01] [9.74093474e-02] [5.68505405e-01] [9.65681560e-01] [7.94931731e-01] [7.52893987e-01] [5.43942380e-01] [9.38096939e-01] [8.38066653e-01] [7.83185689e-01] [4.22962615e-02] [2.96843761e-01] [9.50102088e-01] [6.36912393e-01] [3.75066692e-03] [6.03600756e-01] [4.22466907e-01] [3.23442622e-01] [7.23251484e-02] [1.49598420e-01] [5.45714254e-01] [9.59122727e-01]] ......... After concatenate: [[[0.24278948 0.41363799 0.00761597] [0.4922528 0.8033311 0.73833312] [0.93344881 0.55224706 0.72935665] ... [0.14959842 0.26294052 0.63326384] [0.54571425 0.82177763 0.7713901 ] [0.95912273 0.39791879 0.7461949 ]] [[0.58204652 0.28280547 0.32875312] [0.05928564 0.63875077 0.85676908] [0.02107624 0.37230817 0.32580032] ... [0.81238835 0.16140993 0.79200889] [0.01420085 0.77062809 0.56002668] [0.34129681 0.60455665 0.91487593]] [[0.61701713 0.53000888 0.91511595] [0.59898594 0.74249711 0.26521013] [0.17960885 0.93751794 0.65149374] ... [0.57535478 0.35775559 0.37634059] [0.85069491 0.80337115 0.21084745] [0.5365623 0.512
Explanation:
arr1 = np.random.random(size=(25, 25, 1))
arr2 = np.random.random(size=(25, 25, 1))
arr3 = np.random.random(size=(25, 25, 1))
The above three statements create three 3D NumPy arrays (arr1, arr2, arr3) with shape (25, 25, 1). The elements are random numbers between 0 and 1 generated by the np.random.random() function.
result = np.concatenate((arr1, arr2, arr3), axis=-1): This line concatenate the three arrays along the last axis (axis=-1) using the np.concatenate() function. Since the last axis has size 1, concatenating the three arrays along this axis will create a new array with shape (25, 25, 3).
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics