w3resource

NumPy: Join a sequence of arrays along a new axis

NumPy: Array Object Exercise-121 with Solution

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: Join a sequence of arrays along a new axis

Python-Numpy Code Editor:

Previous: Write a NumPy program to get the index of a maximum element in a numpy array along one axis.
Next: Write a NumPy program to find the index of the sliced elements as follows from a give 4x4 array.

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.