简体   繁体   English

如何将一个 ndarray 插入另一个 ndarray?

[英]How to insert one ndarray to another ndarray?

These are two ndarray.这是两个ndarray。

A=[[1,2,3],[4,5,6],[7,8,9]]

B=[[31,42,53],[11,17,29],[100,59,32]]

How to make a new ndarray 'C' by merge two ndarray A and B?如何通过合并两个 ndarray A 和 B 来制作新的 ndarray 'C'?

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

Using array-initialization to achieve that interweaving task -使用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 run -样品运行 -

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]])

If A and B are of same shapes, we can also stack and reshape -如果AB的形状相同,我们也可以堆叠和重塑 -

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]])

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

you can use numpy library.你可以使用 numpy 库。 like this:像这样:

import numpy as np
A=[[1,2,3],[4,5,6],[7,8,9]]
B=[[31,42,53],[11,17,29],[100,59,32]]
C= np.concatenate((A, B), axis=0)

more information about concatenate with numpy in this link : https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.concatenate.html在此链接中有关与 numpy 连接的更多信息: https : //docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.concatenate.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM