w3resource

NumPy: Stack arrays in sequence vertically

NumPy: Array Object Exercise-128 with Solution

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.

Python-Numpy Code Editor:

Previous: Write a NumPy program to stack arrays in sequence horizontally (column wise).
Next: Write a NumPy program to stack 1-D arrays as columns wise.

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.