Numpy中vstack与hstack函数源码

vstack与hstack函数

Numpy中用来拼接数组的基础函数。

  • vstack( vertical stack):将多个数组沿竖直方向拼接
  • hstack( horizontal stack):将多个数组沿水平方向拼接
In [137]    a=np.array([[1, 2, 4, 5],[1, 2, 4, 5]])
            b=np.array([[3, 4, 6, 7],[3, 4, 6, 7]])
            print('Vertical stack\n', np.vstack((a,b))) #沿竖直方向拼接
            print('Horizontal stack\n', np.hstack((a,b)))#沿水平方向拼接
Out[137]
            Vertical stack
             [[1 2 4 5]
             [1 2 4 5]
             [3 4 6 7]
             [3 4 6 7]]
            Horizontal stack
             [[1 2 4 5 3 4 6 7]
             [1 2 4 5 3 4 6 7]]

vstack与hstack源码

博主自己实现的代码(针对两个数组的,多个数组可以基于此迭代),有更好的实现方式博友可以留言(调用np.concatenate/tile的类似成熟函数勿留言),主要运用了append、shape和reshape函数。reshape(c,-1)用法可参考博主的另一篇博文。

def hstack_(rep):
    """
    function of hstack_ is same as the np.hstack
    created by Master ShiWei at Shanghai University on April 25, 2019
    link and more details: https://blog.csdn.net/W_weiying/article/details/89505153
    """
    if len(rep[0].shape)>1 and len(rep[1].shape)>1: # 判断数组维数
        blank=list()
        for i in range(rep[0].shape[0]):
            blank.append(np.append(rep[0][i],rep[1][i]))
        return np.array(blank)
    else:
        return np.append(rep[0],rep[1])
def vstack_(rep):
    """
    function of vstack_ is same as the np.vstack
    created by Master ShiWei at Shanghai University on April 25, 2019
    link and more details: https://blog.csdn.net/W_weiying/article/details/89505153
    """
    if len(rep[0].shape)>1 and len(rep[1].shape)>1: # 判断数组维数
        return np.append(rep[0],rep[1]).reshape(-1, rep[0].shape[1])
    elif len(rep[0].shape)>1 and len(rep[1].shape)==1:
        return np.append(rep[0],rep[1]).reshape(-1, rep[1].shape[0])
    elif len(rep[0].shape)==1 and len(rep[1].shape)>1:
        return np.append(rep[0],rep[1]).reshape(-1, rep[0].shape[0])

 

你可能感兴趣的:(Python数据分析,python,PYTHON之数据分析)