The concatenate() function is a function from the NumPy package. This function essentially combines NumPy arrays together. This function is basically used for joining two or more arrays of the same shape along a specified axis. There are the following things which are essential to keep in mind:
The concatenate() function is usually written as np.concatenate(), but we can also write it as numpy.concatenate(). It depends on the way of importing the numpy package, either import numpy as np or import numpy, respectively.
numpy.concatenate((a1, a2, ...), axis)
1) (a1, a2, ...)
This parameter defines the sequence of arrays. Here, a1, a2, a3 ... are the arrays which have the same shape, except in the dimension corresponding to the axis.
2) axis : int(optional)
This parameter defines the axis along which the array will be joined. By default, its value is 0.
It will return a ndarray containing the elements of both the arrays.
import numpy as np x=np.array([[1,2],[3,4]]) y=np.array([[12,30]]) z=np.concatenate((x,y)) z
In the above code
In the output, values of both the arrays, i.e., 'x' and 'y' shown as per the axis=0.
Output:
import numpy as np x=np.array([[1,2],[3,4]]) y=np.array([[12,30]]) z=np.concatenate((x,y), axis=0) z
Output:
import numpy as np x=np.array([[1,2],[3,4]]) y=np.array([[12,30]]) z=np.concatenate((x,y.T), axis=1) z
Output:
In the above example, the '.T' used to change the rows into columns and columns into rows.
import numpy as np x=np.array([[1,2],[3,4]]) y=np.array([[12,30]]) z=np.concatenate((x,y), axis=None) z
Output:
In the above examples, we have used np.concatenate() function. This function is not preserved masking of MaskedArray inputs. There is the following way through which we can concatenate the arrays that can preserve masking of MaskedArray inputs.
import numpy as np x=np.ma.arange(3) y=np.arange(3,6) x[1]=np.ma.masked x y z1=np.concatenate([x,y]) z2=np.ma.concatenate([x,y]) z1 z2
In the above code
In the output, values of both the arrays 'z1' and 'z2' have preserved the masking of MaskedArray input.
Output: