In practice, I encountered the operation of matrix stacking. I originally wanted to write a function myself. Later, I thought that there should be a library function, so I searched for it
import numpy as np a = np.array([1,2,3]) b = np.array([4,5,6]) np.stack ((a, b)) ා default row stack Output: array([[1, 2, 3], [4, 5, 6]]) np.vstack((a, b)) Output: array([[1, 2, 3], [4, 5, 6]]) np.hstack((a, b)) Output: array([1, 2, 3, 4, 5, 6])
Briefly explain the above code: in fact, it is mainly a function, stack (), which actually contains various stacking methods. Our example is for two-dimensional matrix, in fact, most of our operations are for two-dimensional matrix. For convenience, we define two functions vstack() to vertically stack (vertically) ）, hsstack() to stack horizontally
The stack() function has a parameter, axis, which can set the stack dimension. The default value is 0. In fact, it has the same effect as vstack(). When it is set to 1, the result is as follows
np.stack((a,b),axis=1) Output: array([[1, 4], [2, 5], [3, 6]])
From the perspective of effect, it is equivalent to taking the second dimension of a, that is, column by column, and assembling a matrix by row.
So, can the effect of hstack() be realized by stack()? I haven’t explored it here. Welcome to know about the guidance of children’s boots, but the effect of hstack() is the same as that of concatenate
np.concatenate((a,b)) Output: array([1, 2, 3, 4, 5, 6])
The above example of Python numpy matrix stacking is the whole content shared by Xiaobian. I hope I can give you a reference, and I hope you can support developeppaer more.