Python numpy函数中易混淆的stack(),vstack(),hstack(),dstack()和concatenate()简要分析

stack()    在指定的轴上进行大量数组的堆叠

>>> arrays = [np.random.randn(3, 4) for _ in range(10)]  
>>> np.stack(arrays, axis=0).shape  
(10, 3, 4)  
  
>>>  
  
>>> np.stack(arrays, axis=1).shape  
(3, 10, 4)  
  
>>>  
  
>>> np.stack(arrays, axis=2).shape  
(3, 4, 10)  
  
>>>  
  
>>> a = np.array([1, 2, 3])  
>>> b = np.array([2, 3, 4])  
>>> np.stack((a, b))  
array([[1, 2, 3],  
       [2, 3, 4]])  
  
>>>  
  
>>> np.stack((a, b), axis=-1)  
array([[1, 2],  
       [2, 3],  
       [3, 4]])  

hstack()    horizontally水平方向上进行堆叠 

>>> a = np.array((1,2,3))  
>>> b = np.array((2,3,4))  
>>> np.hstack((a,b))  
array([1, 2, 3, 2, 3, 4])  
>>> a = np.array([[1],[2],[3]])  
>>> b = np.array([[2],[3],[4]])  
>>> np.hstack((a,b))  
array([[1, 2],  
       [2, 3],  
       [3, 4]])  

 vstack()   vertical 竖直方向上进行堆叠

>>> a = np.array([[1], [2], [3]])  
>>> b = np.array([[2], [3], [4]])  
>>> np.vstack((a,b))  
array([[1],  
       [2],  
       [3],  
       [2],  
       [3],  
       [4]])  

dstack()    depth深度方向上进行堆叠

>>> a = np.array((1,2,3))  
>>> b = np.array((2,3,4))  
>>> np.dstack((a,b))  
array([[[1, 2],  
        [2, 3],  
        [3, 4]]])  
  
>>>  
  
>>> a = np.array([[1],[2],[3]])  
>>> b = np.array([[2],[3],[4]])  
>>> np.dstack((a,b))  
array([[[1, 2]],  
       [[2, 3]],  
       [[3, 4]]]) 

concatenate()     在指定的轴上进行少量数组的堆叠

np.concatenate(tup, axis=i)     i=0,1,2 时分别对应hstack,vstack,dstack

猜你喜欢

转载自blog.csdn.net/qq_41853758/article/details/81079512