Python NumPy For Your Grandma - 4.4 concatenate()

Contents

In this section, we’ll see how you can use the concatenate() function to combine two or more arrays.

This function takes two primary arguments. The first is a sequence of arrays you wanna combine, usually a tuple or a list. The second argument, axis, specifies the axis along which you want to combine the arrays. For example if the arrays are two dimensional, do you want to combine their rows (axis 0) or their columns (axis 1)? NumPy uses axis 0 by default. Let’s see an example.

Here we’ll make a 3x2 array called roux and a 2x2 array called gumbo

import numpy as np

roux = np.zeros(shape = (3,2))
print(roux)
## [[0. 0.]
##  [0. 0.]
##  [0. 0.]]
gumbo = np.ones(shape = (2,2))
print(gumbo)
## [[1. 1.]
##  [1. 1.]]

We can combine roux with a couple copies of itself row-wise

np.concatenate((roux, roux, roux), axis = 0)
## array([[0., 0.],
##        [0., 0.],
##        [0., 0.],
##        [0., 0.],
##        [0., 0.],
##        [0., 0.],
##        [0., 0.],
##        [0., 0.],
##        [0., 0.]])

or column-wise.

np.concatenate((roux, roux, roux), axis = 1)
## array([[0., 0., 0., 0., 0., 0.],
##        [0., 0., 0., 0., 0., 0.],
##        [0., 0., 0., 0., 0., 0.]])

We could also combine roux and gumbo row-wise.

np.concatenate((roux, gumbo), axis = 0)
## array([[0., 0.],
##        [0., 0.],
##        [0., 0.],
##        [1., 1.],
##        [1., 1.]])

But, as you might expect, we’ll get an error if we try to combine them column-wise because they don’t have the same number of rows. In general, when you concatenate arrays, they must have the same exact shape excluding the axis along which you’re concatenating.

np.concatenate((roux, gumbo), axis = 1)  # error