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

I wanna get the concatenate result as:

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

how can I do this?

Divakar
  • 218,885
  • 19
  • 262
  • 358
MarStarck
  • 433
  • 7
  • 14

3 Answers3

1

Here's one approach with few repeats and then stacking -

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

Sample run -

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

One more initialization based -

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   

Runtime test -

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
Divakar
  • 218,885
  • 19
  • 262
  • 358
0

Using np.indices and np.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]])
Daniel F
  • 13,620
  • 2
  • 29
  • 55
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
RedEyed
  • 2,062
  • 1
  • 23
  • 26