NumPy: Join a sequence of arrays along a new axis
Join Arrays Along New Axis
Write a NumPy program to join a sequence of arrays along an axis.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating NumPy arrays 'x' and 'y' containing elements
x = np.array([1, 2, 3])
y = np.array([2, 3, 4])
# Printing a message indicating the original arrays will be displayed
print("Original arrays:")
# Displaying the original arrays 'x' and 'y'
print(x)
print(y)
# Printing a message indicating a sequence of arrays along a new axis will be displayed
print("Sequence of arrays along a new axis:")
# Stacking arrays 'x' and 'y' vertically to form a new array along a new axis using np.vstack()
print(np.vstack((x, y)))
# Creating 2D arrays 'x' and 'y' containing elements in separate rows
x = np.array([[1], [2], [3]])
y = np.array([[2], [3], [4]])
# Printing a message indicating the original arrays will be displayed
print("\nOriginal arrays:")
print(x)
print()
print(y)
# Printing a message indicating a sequence of arrays along a new axis will be displayed
print("Sequence of arrays along a new axis:")
# Stacking arrays 'x' and 'y' vertically to form a new array along a new axis using np.vstack()
print(np.vstack((x, y)))
Sample Output:
Original arrays: [1 2 3] [2 3 4] Sequence of arrays along a new axis: [[1 2 3] [2 3 4]] Original arrays: [[1] [2] [3]] [[2] [3] [4]] Sequence of arrays along a new axis: [[1] [2] [3] [2] [3] [4]]
Explanation:
In the above example -
x = np.array([1, 2, 3]) and y = np.array([2, 3, 4]): Create two 1D NumPy arrays x and y.
np.vstack((x, y)) - Vertically stack x and y using the np.vstack() function. This will create a new 2D array where x is the first row and y is the second row.
x = np.array([[1], [2], [3]]) and y = np.array([[2], [3], [4]]): Create two 2D NumPy arrays x and y, each with 3 rows and 1 column.
np.vstack((x, y)) - Vertically stack x and y using the np.vstack() function. This will create a new 2D array with 6 rows and 1 column, where the rows of y are appended below the rows of x.
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics