2017-09-07 4 views
1
a = np.array([[1,1],[2,2]]) 
b = np.array([[3,3], [4,4]]) 

Je veux obtenir le résultat concaténer comme:Comment concaténer deux tableau numpy a, b comme celui-ci

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

comment puis-je faire cela?

+1

'[x + y pour x, y dans iterools.product (a, b)]' ferait –

+0

@Divakar peut être facilement fait avec 'itertools.product '. N'hésitez pas à rouvrir si vous pensez que ce n'est pas un ajustement parfait. –

Répondre

1

est ici une approche avec quelques répétitions, puis l'empilage -

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 

run Exemple -

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

Encore une initialisation à base -

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 

Test d'exécution -

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 
0

En utilisant np.indices et 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]]) 
+0

Plus lent que @Divakar, mais extensible à plus de baies. –

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