numpy.concatenate() in PythonThe 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. SyntaxParameters1) (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. ResultIt will return a ndarray containing the elements of both the arrays. Example 1: numpy.concatenate()In the above code
In the output, values of both the arrays, i.e., 'x' and 'y' shown as per the axis=0. Output: array([[ 1, 2], [ 3, 4], [12, 30]]) Example 2: numpy.concatenate() with axis=0Output: array([[ 1, 2], [ 3, 4], [12, 30]]) Example 3: numpy.concatenate() with axis=1Output: array([[ 1, 2, 12], [ 3, 4, 30]]) In the above example, the '.T' used to change the rows into columns and columns into rows. Example 4: numpy.concatenate() with axis=NoneOutput: array([ 1, 2, 3, 4, 12, 30]) 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. Example 5: np.ma.concatenate()In the above code
In the output, values of both the arrays 'z1' and 'z2' have preserved the masking of MaskedArray input. Output: masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) array([3, 4, 5]) masked_array(data=[0, 1, 2, 3, 4, 5], mask=False, fill_value=999999) masked_array(data=[0, --, 2, 3, 4, 5], mask=[False, True, False, False, False, False], fill_value=999999) Next Topicnumpy.append() in Python |