w3resource

NumPy: Stack arrays in sequence vertically


Stack Arrays Vertically

Write a NumPy program to stack arrays vertically.

Pictorial Presentation:

NumPy: Stack arrays in sequence vertically

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 3x3 NumPy array 'x' with elements from 0 to 8 using np.arange() and reshaping it
x = np.arange(9).reshape(3, 3)

# Creating another 3x3 NumPy array 'y' by multiplying each element of 'x' by 3
y = x * 3

# Printing a message for Array-1 and displaying the original 3x3 array 'x'
print("Array-1")
print(x)

# Printing a message for Array-2 and displaying the modified 3x3 array 'y' (each element multiplied by 3)
print("Array-2")
print(y)

# Stacking Array-1 'x' and Array-2 'y' vertically using np.vstack()
new_array = np.vstack((x, y))

# Printing a message indicating the vertical stacking of arrays and displaying the new vertically stacked array
print("\nStack arrays in sequence vertically:")
print(new_array) 

Sample Output:

Original arrays:
Array-1
[[0 1 2]
 [3 4 5]
 [6 7 8]]
Array-2
[[ 0  3  6]
 [ 9 12 15]
 [18 21 24]]

Stack arrays in sequence vertically:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 0  3  6]
 [ 9 12 15]
 [18 21 24]]

Explanation:

In the above code -

x = np.arange(9).reshape(3,3): This line creates an array with values from 0 to 8 (9 values) using np.arange(9), and then reshapes it into a 3x3 array using reshape(3,3).

y = x*3: It performs element-wise multiplication of the x array by 3.

new_array = np.vstack((x, y)): It vertically stacks the two 3x3 arrays x and y, resulting in a new 6x3 array new_array:

Finally, print() function prints the vertically stacked new_array.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to vertically stack two arrays using np.vstack and verify the final array dimensions.
  • Create a function that merges multiple 2D arrays row-wise and checks that the row order is maintained.
  • Test vertical stacking on arrays with inconsistent column counts and handle the exceptions.
  • Implement a solution that demonstrates the difference between np.vstack and np.concatenate along axis=0.

Go to:


PREV : Stack Arrays Horizontally
NEXT : Stack 1D Arrays as Columns


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.