np.concatenate
is used for concatenating numpy arrays.
We will discuss here some of the functionalities of this method of numpy arrays.
It takes a list of two or more arrays as input argument, and some other keyword arguments, one of which we will cover here.
Simplest usage of the concatenate
method is as follows:
import numpy as np
# make two arrays
a = np.array([1,2,3])
b = np.array([4,5,6])
# concatenate
c = np.concatenate([a,b], axis=0)
# print all the arrays and their shapes
print('\n\n', a)
print('\n\n', b)
print('\n\n', c)
print('\nshape of a = ', c.shape)
print('\nshape of b = ', c.shape)
print('\nshape of c = ', c.shape)
a:
[1 2 3]
b:
[4 5 6]
c:
[1 2 3 4 5 6]
shape of a = (6,)
shape of b = (6,)
shape of c = (6,)
Both of the inputs in above code are one dimensional. Hence, they have just one axis. np.concatenate
has keyword argument, axis
, whose default value is 0
. In the above code, we have written it explicitly for clarity.
Let’s generate similar array of 2 dimensions. For this we need to provide the list
of numbers inside a list
to the np.array
method.
a = np.array([[1,2,3]])
b = np.array([[4,5,6]])
print('\n\nshape of a = ', a.shape)
shape of a = (1, 3)
We can now see that the shape of the arrays a
, and b
is (1,3),
meaning they have 1 row and 3 columns.
The rows correspond to the 0 (zeroth) axis and the columns correspond
to the 1 (first) axis.
Let’s now say we want to stack the two arrays on top of each other. The resultant array should give us two rows and three columns.
We use the concatenate
method as follows:
c = np.concatenate([a,b], axis=0)
print('\n\na:\n', a)
print('\n\nb:\n', b)
print('\n\nc:\n', c)
print('\n\nshape of c = ', c.shape)
a:
[[1 2 3]]
b:
[[4 5 6]]
c:
[[1 2 3]
[4 5 6]]
shape of c = (2, 3)
To stack the two arrays side ways to get an array of shape, (1,6), make
the value of keyword argument, axis
equal to ‘1’.
c = np.concatenate([a,b], axis=1)
print('\n\na:\n', a)
print('\n\nb:\n', b)
print('\n\nc:\n', c)
print('\n\nshape of c = ', c.shape)
a:
[[1 2 3]]
b:
[[4 5 6]]
c:
[[1 2 3 4 5 6]]
shape of c = (1, 6)
When axis=0
, the number of columns in each of the arrays need to be same.
Also, when axis=1
, the number of rows in each of the arrays need to be same.
You may concatenate as many arrays in one statements, provided their shapes are compatible for concatenation.
c = np.concatenate([a,b,a,a,b,a,b], axis=0)
print('\n\na:\n', a)
print('\n\nb:\n', b)
print('\n\nc:\n', c)
print('\n\nshape of c = ', c.shape)
a:
[[1 2 3]]
b:
[[4 5 6]]
c:
[[1 2 3]
[4 5 6]
[1 2 3]
[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]
shape of c = (7, 3)