【问题标题】:How to insert one ndarray to another ndarray?如何将一个ndarray插入另一个ndarray?
【发布时间】:2018-04-12 08:12:59
【问题描述】:

这是两个 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]]

【问题讨论】:

  • 这是 C++ 吗?我看到 numpy 所以 python?你能添加这个语言的标签吗

标签: python numpy multidimensional-array


【解决方案1】:

使用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

示例运行 -

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

如果AB的形状相同,我们也可以stack和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])

【讨论】:

    【解决方案2】:

    你可以使用 numpy 库。像这样:

    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)
    

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

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 2021-03-14
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 2021-06-01
      • 2020-07-31
      相关资源
      最近更新 更多