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

 

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