NumPy array join example

In this tutorial we learn how to join array in numpy code. we learn joining one dimensional array and two dimensional array.

numpy array join

First we define two different array in two variable, and then we join both array using concatenate function.

import numpy as np

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

arr2 = np.array([40, 51, 16])

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

print(arrResult) 

above code will create one single array like [21 12 13 40 51 16]

Concatenate function is used as join, which add all the array objects and convert into one array.

Joining two dimensional array numpy

Like previous example, we also can join two-dimensional arrays, the result will create one two-dimensional array.

import numpy as np

arr2d1 = np.array([[1, 2, 3],[8, 9, 7]])
arr2d2 = np.array([[4, 1, 6],[2, 5, 9]])

arrResult1 = np.concatenate((arr2d1, arr2d2))

print(arrResult1)

the result of above code (will join both arrays) [[1 2 3] [8 9 7] [4 1 6] [2 5 9]]

if you check the result array dimension using ndim property arrResult1.ndim, you will see the result is 2.

Concatenate function also has different overload for joining two-dimension array, where we can define axis axis=1, let's look at the example below.

import numpy as np

arr2d1 = np.array([[1, 2, 3],[8, 9, 7]])
arr2d2 = np.array([[4, 1, 6],[2, 5, 9]])

arrResult1 = np.concatenate((arr2d1, arr2d2),axis=1)

print(arrResult1)

Above code will produce result like [[1 2 3 4 1 6] [8 9 7 2 5 9]]

Stack Functions Joining Arrays in NumPy

Just like concatenate function, we can use stack function to join array in numpy code.

Difference between concatenate and stack:
The only difference staking is done with new axis, also after joining array using stack function the dimension gets change, which never happen with concatenate function.

Let’s join two one dimension array using stack function.

import numpy as np

arr1 = np.array([21, 12, 13])
arr2 = np.array([40, 51, 16])

arrResult = np.stack((arr1, arr2))

print(arrResult) 
print(arrResult.ndim) 

If you see the above result will look like [[21 12 13] [40 51 16]] and become two dimensional array, just check arrResult.ndim property

Now we see the same stack function with just one additional parameter axis=1, that will change the way array gets joined and the result, the following method will join columns in numpy array.

arr1 = np.array([21, 12, 13])
arr2 = np.array([40, 51, 16])

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

print(arrResult) 
print(arrResult.ndim) 

the above stack function will join columns, result [[21 40] [12 51] [13 16]],

Now we see how to join two-dimension array using stack function.

import numpy as np

arr2d1 = np.array([[1, 2, 3],[8, 9, 7]])
arr2d2 = np.array([[4, 1, 6],[2, 5, 9]])

arrResult1 = np.stack((arr2d1, arr2d2),axis=1)

print(arrResult1)
print(arrResult1.ndim)
Python NumPy examples | Join Python Course