Arrays can be combined in various ways. This process in NumPy is referred to as stacking. Stacking can take various forms, including horizontal, vertical, and depth-wise stacking. To demonstrate this, we will use the following two arrays (a
and b
):
In [59]: # creating two arrays for examples a = np.arange(9).reshape(3, 3) b = (a + 1) * 10 a Out[59]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) In [60]: b Out[60]: array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
Horizontal stacking combines two arrays in a manner where the columns of the second array are placed to the right of those in the first array. The function actually stacks the two items provided in a two-element tuple. The result is a new array with data copied from the two that are specified:
In [61]: # horizontally stack the two arrays # b becomes columns of a to the right of a's columns np.hstack((a, b)) Out[61]: array([[ 0, 1, 2, 10, 20...