Skip to main content

Introduction to Python NumPy Joining Array

Python NumPy Joining Array​

In NumPy, you can join or concatenate arrays along different axes using various functions.

Here are some common functions for joining arrays:

Using np.concatenate()​

The np.concatenate() function allows you to join arrays along a specified axis.

It takes a sequence of arrays as input and concatenates them into a single array.

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Join arrays along the first axis (axis=0)
result = np.concatenate((arr1, arr2))
print(result) #Output: [1 2 3 4 5 6]

Using np.stack()​

The np.stack() function stacks arrays along a new axis. It takes a sequence of arrays as input and stacks them along the specified axis.

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Stack arrays along a new axis (axis=0)
result = np.stack((arr1, arr2))
print(result) # Output: [[1 2 3][4 5 6]]

Using np.vstack() and np.hstack()​

The np.vstack() function vertically stacks arrays, while np.hstack() horizontally stacks arrays.

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Vertically stack arrays
vstack_result = np.vstack((arr1, arr2))
print(vstack_result)

# Horizontally stack arrays
hstack_result = np.hstack((arr1, arr2))
print(hstack_result) #Output [[1 2 3][4 5 6]][1 2 3 4 5 6]