np.concatenate() constructor is used to concatenate or join two or more arrays into one. The only required argument is list or tuple of arrays.
π‘For np.concatenate() to work, all the input array dimensions for the concatenation axis must match exactly, other wise you will get ValueError
1.1. 1D arrays
Letβs get straight to work and define two arrays and then join them:
# first, import numpyimport numpy as np# making two arrays to concatenatearr1 = np.arange(1,4)arr2 = np.arange(4,7)print("Arrays to concatenate:")print(arr1);print(arr2)print("After concatenation:")print(np.concatenate([arr1,arr2]))
Arrays to concatenate:
[1 2 3]
[4 5 6]
After concatenation:
[1 2 3 4 5 6]
We can also join more than two arrays:
# we can concatenate more than two arraysarr3 = np.arange(7,10)np.concatenate([arr1,arr2,arr3])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
1.2. nD arrays
The same constructor is used for joining two or more nD arrays
By default, np.concat joins along the row wise (stack on top of each other). However, by providing kwarg axis=1, we can also concatenate along columns.
# creating 2D arrays to joinar2d1 = np.arange(1,7).reshape(2,3)ar2d2 = np.arange(7,13).reshape(2,3)print("2D arrays to concatenate:")print(ar2d1);print(ar2d2)# case1: joining along rowsprint("\nConcatenating along rows:")print(np.concatenate([ar2d1,ar2d2]))# case1: joining along columnsprint("\nConcatenating along columns:")print(np.concatenate([ar2d1,ar2d2], axis=1))
np.vsplit splits along the vertical axis. You can either provide:
integer of equally shaped array (method 1 below), or,
by specifying the row[integer] at which the division should occur (method 2 below)
vs = np.arange(16).reshape(4,4)print(f"Array to vSplit: \n{vs}")# method 1, by specifying number of equally shaped arraysprint("\nUsing Method 1")upper, lower = np.vsplit(vs, 2)print(f"Upper: \n{upper}\nLower: \n{lower}")# method 2, by specifying row, after which division should occurprint("\nUsing Method 2")print(np.vsplit(vs, [2]))
np.hsplit splits along the horizontal axis. You can either provide:
number integer of equally shaped array, or,
by specifying the column[integer] at which the division should occur
hs = np.arange(16).reshape(2,8)print(f"Array to hSplit: \n{hs}")# method 1, by specifying number of equally shaped arraysprint("\nUsing Method 1")right, left = np.hsplit(hs, 2)print(f"Right: \n{right}\nLeft: \n{left}")# method 2, by specifying columns, after which division should occurprint("\nUsing Method 2")print(np.hsplit(hs, [4]))