How To Join Arrays In Numpy
Joining array in numpy means combining two arrays.Like in SQL we used to join tables based on a key value similarly in numpy we used to join arrays based on the axes of the arrays.
To join the arrays we can use the concatenate() function and we can pass the axes value to concatenate function() to join the arrays.If the axes value will not be explicitly passed then it needs to be considered as 0.
How To Join Two 1-D Array In Numpy Python
import numpy as np
arr1 = np.array([7, 8, 9])
arr2 = np.array([6, 5, 4])
arr = np.concatenate((arr1, arr2))
print(arr)
Output:
[1 2 3 4 5 6]
How To Join Two 2-D Array Along With Rows In Numpy Python
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)
Output:
[[1 2 5 6]
[3 4 7 8]]
Explanation:
As we are joining the arrays based on rows so the output for the array is printed based on the rows only.
How To Join Arrays In The Stack Function In Numpy Array
Stacking of the arrays is same like concatenation.The only difference is that stacking is done along a new axis.
For the stack() function we can pass the sequence of the arrays with the axis value.If we will not pass the axis value then by default it will take the axis value as 0.
Let's take a look at the example below
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)
Output:
[[1 4]
[2 5]
[3 6]]
How To Stack Numpy Arrays Along with Rows
In Numpy there is a function called hstack() which stacks the arrays by the rows
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.hstack((arr1, arr2))
print(arr)
Output:
[1 2 3 4 5 6]
How To Stack Numpy Arrays Along Columns
Numpy provides a function called vstack() to stack the Numpy Arrays along the columns
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.vstack((arr1, arr2))
print(arr)
Output:
[[1 2 3]
[4 5 6]]
How To Stack Numpy Arrays Along with Heights(Depth)
Numpy provides a function dstack() to stack the arrays along with the height which is same as depth
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.dstack((arr1, arr2))
print(arr)
Output:
[[[1 4]
[2 5]
[3 6]]]
Comments
Post a Comment
souvikdutta.aec@gmail.com