w3resource

NumPy: Merge three given NumPy arrays of same shape

NumPy: Array Object Exercise-165 with Solution

Write a NumPy program to merge three given NumPy arrays of same shape.

Sample Solution:

Python Code:

import numpy as np
arr1 = np.random.random(size=(25, 25, 1))
arr2 = np.random.random(size=(25, 25, 1))
arr3 = np.random.random(size=(25, 25, 1))
print("Original arrays:")
print(arr1)
print(arr2)
print(arr3)
result = np.concatenate((arr1, arr2, arr3), axis=-1)
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

Pictorial Presentation:

NumPy: Merge three given NumPy arrays of same shape

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to save as text a matrix which has in each row 2 float and 1 string at the end.
Next: Write a NumPy program to combine last element with first element of two given ndarray with different shapes.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}