Given two NumPy arrays
b. How to concatenate both?
Method 1: np.concatenate()
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()
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
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()
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]] '''
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.)
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.