w3resource

NumPy: Convert two 1-D arrays into a 2-D array


Depth-Wise Conversion of 1D to 2D

Write a NumPy program to convert (in sequence depth wise (along the third axis)) two 1-D arrays into a 2-D array.
Sample array: (10,20,30), (40,50,60)

Pictorial Presentation:

Python NumPy: Convert two 1-D arrays into a 2-D array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating NumPy arrays 'a' and 'b' with vertical shapes
a = np.array([[10], [20], [30]])
b = np.array([[40], [50], [60]])

# Stacking arrays 'a' and 'b' along the third axis using np.dstack
c = np.dstack((a, b))

# Printing the resulting array 'c'
print(c)

Sample Output:

[[[10 40]]                                                             
                                                                       
 [[20 50]]                                                             
                                                                       
 [[30 60]]] 

Explanation:

‘a = np.array([[10],[20],[30]])’ creates a 2D array a with shape (3, 1).

‘b = np.array([[40],[50],[60]])’ This line creates another 2D array b with shape (3, 1).

c = np.dstack((a, b)): The np.dstack() function is used to stack the two arrays ‘a’ and ‘b’ depth-wise along the third axis. The resulting array ‘c’ has the shape (3, 1, 2), where the first depth layer contains the elements of a and the second depth layer contains the elements of ‘b’.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to merge two 1D arrays into a 2D array along a new depth axis using np.dstack.
  • Stack two 1D arrays depth-wise and verify that the resulting shape matches the expected 3D structure.
  • Create a function that takes two 1D arrays and returns a depth-wise combined 2D array with an added axis.
  • Use np.concatenate with an axis parameter to simulate depth stacking of two 1D arrays.

Go to:


PREV : Convert 1D Arrays to 2D (as Columns)
NEXT : Split 14 Elements into 3 Arrays


Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.