w3resource

NumPy: Stack 1-D arrays as row wise


Stack 1D Arrays as Rows

Write a NumPy program to stack 1-D arrays row wise.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Printing a message indicating the original arrays will be displayed
print("\nOriginal arrays:")

# Creating a NumPy array 'x' with elements 1, 2, and 3
x = np.array((1, 2, 3))

# Creating another NumPy array 'y' with elements 2, 3, and 4
y = np.array((2, 3, 4))

# Printing a message for Array-1 and displaying the contents of array 'x'
print("Array-1")
print(x)

# Printing a message for Array-2 and displaying the contents of array 'y'
print("Array-2")
print(y)

# Stacking Array-1 'x' and Array-2 'y' as rows using np.row_stack()
new_array = np.row_stack((x, y))

# Printing a message indicating the stacking of 1-D arrays as rows and displaying the resulting new array
print("\nStack 1-D arrays as rows wise:")
print(new_array) 

Sample Output:

Original arrays:
Array-1
[1 2 3]
Array-2
[2 3 4]

Stack 1-D arrays as rows wise:
[[1 2 3]
 [2 3 4]]

Explanation:

In the above code -

  • x = np.array((1,2,3)): It creates a 1-dimensional NumPy array x with the elements 1, 2, and 3.
  • y = np.array((2,3,4)): It creates another 1-dimensional NumPy array y with the elements 2, 3, and 4.
  • new_array = np.row_stack((x, y)): It stacks the two 1-dimensional arrays x and y row-wise to form a new 2-dimensional array new_array.
  • Finally print() function prints the new_array.

Pictorial Presentation:

Python NumPy: Stack 1-D arrays as row wise.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to stack 1D arrays as rows using np.vstack and verify the output shape.
  • Create a function that accepts multiple 1D arrays and returns a 2D array where each array is a row.
  • Test the row stacking on arrays and check that the sequence of elements is maintained.
  • Implement a solution that contrasts np.vstack with np.row_stack for stacking 1D arrays.

Go to:


PREV : Stack 1D Arrays as Columns
NEXT : Split Array Vertically


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.