لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

Python Data Science NumPy Joining Array

Joining NumPy Arrays

Joining means putting contents of two or more arrays in a single array.

In SQL we join tables based on a key, whereas in NumPy we join arrays by axis.

We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis. If axis is not explicitly passed,
it is taken as 0.

Example 1: Join two arrays

Code

import numpy as np

arr1 = np.array([11, 12, 13])

arr2 = np.array([14, 15, 16])

arr = np.concatenate((arr1, arr2))

print(arr)

the output will be

[11 12 13 14 15 16]

Example 2: Join two 2-D arrays along rows (axis=1).

Code

import numpy as np

arr1 = np.array([[11, 12], [13, 14]])

arr2 = np.array([[15, 16], [17, 18]])

arr = np.concatenate((arr1, arr2), axis=1)

print(arr)

the output will be

[[11 12 15 16]
 [13 14 17 18]]    


Joining Arrays Using Stack Functions

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

We can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking.

We pass a sequence of arrays that we want to join to the stack() method along with the axis. If axis is not explicitly passed it is taken as 0.

Example 3: Concatenate two 1-D arrays along the second axis.

Code

import numpy as np

arr1 = np.array([11, 12, 13])

arr2 = np.array([14, 15, 16])

arr = np.stack((arr1, arr2), axis=1)

print(arr)

the output will be

[[11 14]
 [12 15]
 [13 16]]    


Stacking Along Rows

NumPy provides a helper function which is known as hstack() to stack along rows.

Example 4: Use hstack() to stack method to join array along rows.

Code

import numpy as np

arr1 = np.array([11, 12, 13])

arr2 = np.array([14, 15, 16])

arr = np.hstack((arr1, arr2))

print(arr)

the output will be

[11 12 13 14 15 16]

Stacking Along Columns

NumPy provides a helper function vstack() to stack along columns.

Example 5: Use vstack() to stack method to join array along columns.

Code

import numpy as np

arr1 = np.array([11, 12, 13])

arr2 = np.array([14, 15, 16])

arr = np.vstack((arr1, arr2))

print(arr)

the output will be

[[11 12 13]
 [14 15 16]]    


Stacking Along Height (depth)

NumPy provides a helper function dstack() to stack along height, which is the same as depth.

Example 6: Use vstack() to stack method to join array along height/depth.


Code

import numpy as np

arr1 = np.array([11, 12, 13])

arr2 = np.array([14, 15, 16])

arr = np.dstack((arr1, arr2))

print(arr)

the output will be

[[[11 14]
  [12 15]
  [13 16]]]