NumPy Array Joining

Join NumPy arrays

Joining means placing the contents of two or more arrays into a single array.

In SQL, we join tables based on keys, while in NumPy, we join arrays along an axis.

We pass a series of arrays to be connected to the axis concatenate() The array function. If the axis is not explicitly passed, it is considered 0.

Example

Connect two arrays:

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2))
print(arr)

Run Instance

Example

Connect two 2-D arrays along the row (axis=1):

import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
arr = np.concatenate((arr1, arr2), axis=1)
print(arr)

Run Instance

Connecting arrays using the stacking function

Stacking is the same as concatenation, the only difference is that stacking is done along a new axis.

We can connect two one-dimensional arrays along the second axis, which will result in them overlapping with each other, that is, stacking (stacking).

We pass a series of arrays to be connected to the axis concatenate() The array of methods. If the axis is not explicitly passed, it is considered to be 0.

Example

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.stack((arr1, arr2), axis=1)
print(arr)

Run Instance

Stacked along rows

NumPy provides an auxiliary function:hstack() Stacked along rows.

Example

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.hstack((arr1, arr2))
print(arr)

Run Instance

Stacked along columns

NumPy provides an auxiliary function:vstack() Stacked along columns.

Example

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.vstack((arr1, arr2))
print(arr)

Run Instance

Stacked along the height (depth)

NumPy provides an auxiliary function:dstack() Stacked along the height, the height is the same as the depth.

Example

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.dstack((arr1, arr2))
print(arr)

Run Instance