如何连接两个numpy数组a,b像这样

时间:2017-09-07 09:57:33

标签: python numpy multidimensional-array concatenation

a = np.array([[1,1],[2,2]])
b = np.array([[3,3], [4,4]])

我想得到连接结果:

([[1,1,3,3], [1,1,4,4], [2,2,3,3], [2,2,4,4]])

我该怎么做?

3 个答案:

答案 0 :(得分:1)

这是一种几乎没有重复然后堆叠的方法 -

def repeat_stack(a, b):
    a_ext = np.repeat(a, len(b),axis=0)
    b_ext = np.repeat(b[None], len(a),axis=0).reshape(-1,b.shape[1])
    return np.c_[a_ext, b_ext] # or use np.column_stack

示例运行 -

In [564]: a
Out[564]: 
array([[1, 1],
       [2, 2],
       [5, 5]]) # added one more row for variety

In [565]: b
Out[565]: 
array([[3, 3],
       [4, 4]])

In [23]: repeat_stack(a, b)
Out[23]: 
array([[1, 1, 3, 3],
       [1, 1, 4, 4],
       [2, 2, 3, 3],
       [2, 2, 4, 4],
       [5, 5, 3, 3],
       [5, 5, 4, 4]])

再基于一次初始化 -

def initialization_app(a, b):
    ma,na = a.shape
    mb,nb = b.shape
    out = np.empty((ma,mb,na+nb), dtype=np.result_type(a,b))
    out[:,:,:na] = a[...,None]
    out[:,:,na:] = b
    out.shape = (-1, out.shape[-1])
    return out   

运行时测试 -

In [16]: a = np.random.randint(0,9,(100,100))

In [17]: b = np.random.randint(0,9,(100,100))

In [18]: %timeit repeat_stack(a, b)
100 loops, best of 3: 5.85 ms per loop

In [19]: %timeit initialization_app(a, b)
1000 loops, best of 3: 1.81 ms per loop

答案 1 :(得分:0)

使用np.indicesnp.hstack

def product_2d(*args):
    idx = np.indices((arg.shape[0] for arg in args))
    return np.hstack([arg[idx[i].flatten()] for i, arg in enumerate(args)])

product_2d(a, b)

array([[1, 1, 3, 3],
       [1, 1, 4, 4],
       [2, 2, 3, 3],
       [2, 2, 4, 4]])

答案 2 :(得分:0)

import numpy as np
a = np.array([[1,1], [2,2]]) 
b = np.array([[3,3], [4,4]])

shape = np.add(np.array(a.shape), np.array(b.shape))
c = np.zeros(shape)

k = 0
for i in range(len(a)):
    for j in range(len(b)):
        c[k, :] = np.concatenate((a[i], b[j]))
        k += 1

c