The NumPy concatenate() method joins a sequence of arrays along an existing axis.
concatenate() Syntax
The syntax of concatenate() is:
numpy.concatenate((array1, array2, …), axis, out)
concatenate() Arguments
The concatenate() method takes the following arguments:
(array1, array2, …)- the sequence of arrays to be joinedaxis(optional)- defines the dimension in which the arrays are joinedout(optional) - destination to place the result.dtype(optional) - datatype of the resultant array
Notes:
- All the input arrays' dimensions except for the concatenation axis must match exactly.
- Only one of
outanddtypearguments can be passed.
concatenate() Return Value
The concatenate() method returns the joined array.
Example 1: Concatenate Two Arrays
Output
[[1 2] [3 4] [5 6]] [[1 2] [3 4] [5 6]]
If we do not pass the axis argument, the value of axis will be 0 by default.
Example 2: Concatenate Two Arrays in Different Dimensions
Output
Joining the array when axis = 0 [[[ 0 1] [ 2 3]] [[ 4 5] [ 6 7]] [[10 11] [12 13]] [[14 15] [16 17]]] Joining the array when axis = 1 [[[ 0 1] [ 2 3] [10 11] [12 13]] [[ 4 5] [ 6 7] [14 15] [16 17]]] Joining the array when axis = 2 [[[ 0 1 10 11] [ 2 3 12 13]] [[ 4 5 14 15] [ 6 7 16 17]]]
Example 3: Concatenate Flattened Arrays
If we pass None as the axis argument, concatenate() flattens the arrays and concatenates them.
Output
Output: [ 0 1 2 3 10 11 12 13]
Note: We can also use numpy.append() to concatenate arrays. However, unlike numpy.concatenate, numpy.append creates a new copy with appended values, making it less efficient.
Example 4: Return an Existing Array as Concatenated Array
In our previous examples, concatenate() created a new array as a result.
However, passing an existing array as the argument stores the resultant array as the given array.
Output
[[ 0. 1.] [ 2. 3.] [10. 11.] [12. 13.]]
Notes:
- The shape of the output array must match the shape of the concatenated array otherwise, we will get an error.
- All the input array dimensions remain the same (except for the concatenation axis).
Example 5: Specify the Datatype of a Concatenated Array
We can change the data type of concatenated array by passing the dtype argument.
Output
[['0' '1'] ['2' '3'] ['10' '11'] ['12' '13']]
Related NumPy Methods
- numpy.vstack() concatenates arrays along the axis 0.
- numpy.hstack() concatenates arrays along the axis 1.
- numpy.dstack() concatenates arrays along the axis 2.