开发者社区 问答 正文

交织两个numpy数组

假设给出以下数组:

a = array([1,3,5]) b = array([2,4,6]) 一个人如何有效地将它们交织在一起,以便获得这样的第三个数组

c = array([1,2,3,4,5,6]) 可以假设length(a)==length(b)。 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 21:47:17 633 分享 版权
1 条回答
写回答
取消 提交回答
  • 我需要执行此操作,但要沿任意轴使用多维数组。这是实现此目的的快速通用功能。它具有与相同的调用签名np.concatenate,除了所有输入数组必须具有完全相同的形状。

    import numpy as np

    def interleave(arrays, axis=0, out=None): shape = list(np.asanyarray(arrays[0]).shape) if axis < 0: axis += len(shape) assert 0 <= axis < len(shape), "'axis' is out of bounds" if out is not None: out = out.reshape(shape[:axis+1] + [len(arrays)] + shape[axis+1:]) shape[axis] = -1 return np.stack(arrays, axis=axis+1, out=out).reshape(shape)

    2020-02-08 21:47:34
    赞同 展开评论
问答分类:
问答标签:
问答地址: