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 a new axis.

Sample Solution:

Python Code:

import numpy as np    
x = np.array([1, 2, 3])
y = np.array([2, 3, 4])
print("Original arrays:")
print(x)
print(y)
print("Sequence of arrays along a new axis:")
print(np.vstack((x, y)))
x = np.array([[1], [2], [3]])
y = np.array([[2], [3], [4]])
print("\nOriginal arrays:")
print(x)
print()
print(y)
print("Sequence of arrays along a new axis:")
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]]

Pictorial Presentation:

Python NumPy: Join a sequence of arrays along a new axis

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}