How to Concatenate Two NumPy Arrays?

Problem Formulation

Given two NumPy arrays a and b. How to concatenate both?

Method 1: np.concatenate()

NumPy’s concatenate() method joins a sequence of arrays along an existing axis. The first couple of comma-separated array arguments are joined. If you use the axis argument, you can specify along which axis the arrays should be joined. For example, np.concatenate(a, b, axis=0) joins arrays along the first axis and np.concatenate(a, b, axis=None) joins the flattened arrays.

You can see how the axis argument changes the semantics of the array concatenation:

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])

res_1 = np.concatenate((a, b), axis=0)
print(res_1)
'''
[[1 2]
 [3 4]
 [5 6]]
'''

res_2 = np.concatenate((a, b.T), axis=1)
print(res_2)
'''
[[1 2 5]
 [3 4 6]]
'''

res_3 = np.concatenate((a, b), axis=None)
print(res_3)
'''
[1 2 3 4 5 6]
'''

Note that in the second case, we brought the arrays into a fitting shape via transformation b.T so that we can concatenate the array b as a third column vector.

Method 2: np.append()

NumPy’s append() method appends values to the end of the array. The optional axis argument allows you to append arrays along the specified axis.

The following code shows the same examples as before—just using the append() method instead of the concatenate() method:

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])

res_1 = np.append(a, b, axis=0)
print(res_1)
'''
[[1 2]
 [3 4]
 [5 6]]
'''

res_2 = np.append(a, b.T, axis=1)
print(res_2)
'''
[[1 2 5]
 [3 4 6]]
'''

res_3 = np.append(a, b, axis=None)
print(res_3)
'''
[1 2 3 4 5 6]
'''

Method 3: np.vstack()

NumPy’s vstack() method takes a tuple argument and stacks the arrays in sequence vertically (row wise). This is like concatenating along the first axis after reshaping 1-D arrays of shape (N,) to (1,N).

The following code shows the vertical stack arising from the array concatenation:

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])


res_3 = np.vstack((a, b))
print(res_3)
'''
[[1 2]
 [3 4]
 [5 6]]
'''

Conclusion

This article has demonstrated how to concatenate two arrays in Python using the NumPy library.

Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy