In this tutorial, we will introduce numpy.stack() with some examples. You can learn how to join some arrays by it.
numpy.stack()
It is defined as:
numpy.stack(arrays, axis=0, out=None)
This function will join a sequence of arrays along a new axis.
We should notice a new axis will be added.
Parameters:
arrays: a sequence of arrays, each array must have the same shape.
axis: int, the axis in the result array along which the input arrays are stacked.
How to use numpy.stack()?
Here we will use some examples to show you how to use this function.
Exampe 1: axis = 0
import numpy as np x1 = np.arange(9).reshape((3,3)) x2 = np.arange(10,19,1).reshape((3,3)) y2 = np.stack((x1,x2),axis=0) print(y2)
Here axis = 0, which means we will will join x1 and x2 on axis = 0 in y2.
Run this code, we will see:
[[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[10 11 12] [13 14 15] [16 17 18]]]
x1 and x2 are in axis = 0 of y2.
Example 2: axis = 1
Similar to example 1, we can find x1 and x2 are in axis = 1 of y2.
Here is an example:
import numpy as np x1 = np.arange(9).reshape((3,3)) x2 = np.arange(10,19,1).reshape((3,3)) y2 = np.stack((x1,x2),axis=1) print(y2)
Run this code, we will see:
[[[ 0 1 2] [10 11 12]] [[ 3 4 5] [13 14 15]] [[ 6 7 8] [16 17 18]]]
Example 3:axis = 2
We will get:
[[[ 0 10] [ 1 11] [ 2 12]] [[ 3 13] [ 4 14] [ 5 15]] [[ 6 16] [ 7 17] [ 8 18]]]
Example 4: when we only use x1
Look at this example:
import numpy as np x1 = np.arange(9).reshape((3,3)) print("x1=") print(x1) y2 = np.stack(x1,axis=1) print("y2=") print(y2)
Here parameter arrays is x1 and axis = 1.
Run this code, we will get:
x1= [[0 1 2] [3 4 5] [6 7 8]] y2= [[0 3 6] [1 4 7] [2 5 8]]
Example 5:
import numpy as np x1 = np.arange(9).reshape((3,3)) print("x1=") print(x1) y2 = np.stack([x1],axis=0) print("y2=") print(y2)
Here parameter arrays is [x1] and axis = 0, we will get:
x1= [[0 1 2] [3 4 5] [6 7 8]] y2= [[[0 1 2] [3 4 5] [6 7 8]]]
From example 4 and 5, we can find:
If parameter arrays is an array x1, y2 will not add new axis. However, if arrays is a list [x1], y2 will add a new aixs.