Numpy中concatenate與tile函數詳解

concatenate((a1a2...)axis=0)

實現numpy中數據多個數組(a1,a2,...)的拼接,axis=0沿着垂直方向,axis=1沿着水平方向

In [245]
        a=np.array([[1, 2, 4, 5]])
        b=np.array([[3, 4, 6, 7]])
        print('Horizontal \n',np.concatenate((a,b),axis=1))# 沿水平方向
        print('Vertical \n',np.concatenate((a,b),axis=0))# 沿豎直方向
Out[245]
        Horizontal 
         [[1 2 4 5 3 4 6 7]]
        Vertical 
         [[1 2 4 5]
         [3 4 6 7]]

concatenate函數實現

下面我們簡單編寫了concatenate_函數,其功能與Numpy中的concatenate函數相同,博友們有更好的實現代碼,可以留言。vstack_與hstack_函數源碼見博文 Numpy中vstack與hstack函數源碼

def concatenate_(rep, axis=0):
    """
    function of concatenate_ is same as the np.concatenate
    created by Master ShiWei at Shanghai University on April 26, 2019
    link and more details: https://blog.csdn.net/W_weiying/article/details/89577014
    """
    if axis==0:
        if len(rep)==2:
            return vstack_(rep)
        else:
            temp=vstack_((rep[0],rep[1]))
            for i in range(2,len(rep),1):
                temp=vstack_((temp,rep[i]))
            return temp
    else:
        if len(rep)==2:
            return hstack_(rep)
        else:
            temp=hstack_((rep[0],rep[1]))
            for i in range(2,len(rep),1):
                temp=hstack_((temp,rep[i]))
            return temp

PS:利用concentrate_函數可以實現np.tile 函數功能

def tile_(M, rep):
    """
    function of tile_ is same as the np.tile
    created by Master ShiWei at Shanghai University on April 26, 2019
    link and more details: https://blog.csdn.net/W_weiying/article/details/89505153
    """
    try:
        axis_x=rep[1] # data along x duplicate axis_x times
        axis_y=rep[0] #data along y duplicate axis_y times
        if axis_x==0 or axis_y==0:
            return 'wrong input'
        else:
            if axis_x==1 and axis_y==1:
                return M            
            elif axis_x==1:
                result=M
                for i in range(axis_y-1):
                    result=concatenate_((result,M),axis=0)
                return result
            elif axis_y==1:
                result=M
                for i in range(axis_x-1):
                    result=concatenate_((result,M),axis=1)
                return result
            else:
                result_x=M
                for i in range(axis_x-1):
                    result_x=concatenate_((result_x,M),axis=1)
                result_y=result_x
                for i in range(axis_y-1):
                    result_y=concatenate_((result_y,result_x),axis=0)
                return result_y
    except:
        axis_x=rep
        if axis_x==0:
            return 'wrong input'
        else:
            if axis_x==1:
                return M
            else:
                result=M
                for i in range(axis_x-1):
                    result=concatenate_((result,M),axis=1)
                return result

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章