The concatenate() method is used to join the numpy arrays by passing sequence of arrays along with the axis and in case if axis is not passed it will consider it as 0.
import numpy as np
arr1 = np.array([1, 2])
arr2 = np.array([4, 5])
arr3 = np.concatenate((arr1, arr2))
arr4 = np.array([[1, 2], [3, 4]])
arr5 = np.array([[5, 6], [7, 8]])
arr6= np.concatenate((arr4, arr5), axis=1)
print(arr3)
print(arr6)
Output-
[1 2 4 5]
[[1 2 5 6]
[3 4 7 8]]
Joining Arrays Using Stack Functions-
The stack() method is used for joining two arrays and stacking is same as concatenation, the only difference is that stacking is done along a new axis.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr3 = np.stack((arr1, arr2), axis=1)
print(arr3)
Output-
[[1 4]
[2 5]
[3 6]]
Stacking Along Rows–
The hstack() method is usedย to stack along rows.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr3 = np.hstack((arr1, arr2))
print(arr3)
Output-
[1 2 3 4 5 6]
Stacking Along Columns-
The vstack() method is usedย to stack along columns.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr3 = np.vstack((arr1, arr2))
print(arr3)
Output-
[[1 2 3]
[4 5 6]]
Stacking Along Height (depth)-
The dstack() method is used to stack along height, which is the same as depth.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr3 = np.dstack((arr1, arr2))
print(arr3)
Output-
[[[1 4]
[2 5]
[3 6]]]
Leave a Reply