Skip to main content
 首页 » 编程设计

python之如何将一个数组插入到另一个 ndarray

2024年10月01日7qq78292959

这是两个ndarray。

A=[[1,2,3],[4,5,6],[7,8,9]] 
 
B=[[31,42,53],[11,17,29],[100,59,32]] 

如何通过合并两个 ndarray A 和 B 来创建一个新的 ndarray 'C'?

C=[[1,2,3],[31,42,53],[4,5,6], [11,17,29],[7,8,9],[100,59,32]] 

请您参考如下方法:

使用array-initialization 来实现交织任务 -

def interweave(a, b): 
    N = a.shape[1] 
    M = a.shape[0] + b.shape[0] 
    out_dtype = np.result_type(a.dtype, b.dtype) 
    out = np.empty((M,N),dtype=out_dtype) 
    out[::2] = a 
    out[1::2] = b 
    return out 

sample 运行-

In [274]: A 
Out[274]:  
array([[1, 2, 3], 
       [4, 5, 6], 
       [7, 8, 9]]) 
 
In [275]: B 
Out[275]:  
array([[ 31,  42,  53], 
       [ 11,  17,  29], 
       [100,  59,  32]]) 
 
In [276]: interweave(A, B) 
Out[276]:  
array([[  1,   2,   3], 
       [ 31,  42,  53], 
       [  4,   5,   6], 
       [ 11,  17,  29], 
       [  7,   8,   9], 
       [100,  59,  32]]) 

如果A和B是相同的形状,我们也可以堆叠和 reshape -

In [283]: np.hstack((A,B)).reshape(-1,A.shape[1]) 
Out[283]:  
array([[  1,   2,   3], 
       [ 31,  42,  53], 
       [  4,   5,   6], 
       [ 11,  17,  29], 
       [  7,   8,   9], 
       [100,  59,  32]]) 

或者 np.stack((A,B),axis=1).reshape(-1,A.shape[1])。