how to append a numpy matrix into an empty numpy array

前端 未结 4 1325

I want to append a numpy array(matrix) into an array through a loop

data=[[2 2 2] [3 3 3]]
Weights=[[4 4 4] [4 4 4] [4 4 4]]
All=np.array([])  
for i in data:
           


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-26 09:52

    Option 1: Reshape your initial All array to 3 columns so that the number of columns match h:

    All=np.array([]).reshape((0,3))
    
    for i in data:
        h=i*Weights      
        All=np.concatenate((All,h))
    
    All
    #array([[  8.,   8.,   8.],
    #       [  8.,   8.,   8.],
    #       [  8.,   8.,   8.],
    #       [ 12.,  12.,  12.],
    #       [ 12.,  12.,  12.],
    #       [ 12.,  12.,  12.]])
    

    Option 2: Use a if-else statement to handle initial empty array case:

    All=np.array([])
    for i in data:
        h=i*Weights      
        if len(All) == 0:
            All = h
        else:
            All=np.concatenate((All,h))
    
    All
    #array([[ 8,  8,  8],
    #       [ 8,  8,  8],
    #       [ 8,  8,  8],
    #       [12, 12, 12],
    #       [12, 12, 12],
    #       [12, 12, 12]])
    

    Option 3: Use itertools.product():

    import itertools
    np.array([i*j for i,j in itertools.product(data, Weights)])
    
    #array([[ 8,  8,  8],
    #       [ 8,  8,  8],
    #       [ 8,  8,  8],
    #       [12, 12, 12],
    #       [12, 12, 12],
    #       [12, 12, 12]])
    

提交回复
热议问题