简体   繁体   中英

Combining two unequal arrays

I have created two 1 dimensional, column arrays using numpy - one having 100 cells, and the second 10000 cells. What I want to do now is to write 2 dimensional array having for every cell in first array (the one with 100 elements) written all 10000 values from the second array. Little example explaining it:

a = 
  [[1],
   [2],
   [3]]

b =  
  [[4],
   [5]]

And I'd like to obtain:

c = [[1], [4],
     [1], [5],
     [2], [4],
     [2], [5],
     [3], [4],
     [3], [5]]

I was trying to find any solution, but I was unsuccessful. I hope to find help here. Cheers, Jonh

Is this what you want? I used the function np.repeat to repeat each individual element (first array) and np.tile to repeat the whole array (second array).

>>> import numpy as np
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[4],[5]])
>>> 
>>> at = np.repeat(a, len(b), axis = 0)
>>> at
array([[1],
       [1],
       [2],
       [2],
       [3],
       [3]])
>>> bt = np.tile(b, (len(a), 1))
>>> bt
array([[4],
       [5],
       [4],
       [5],
       [4],
       [5]])
>>> np.concatenate((at, bt), axis = 1)
array([[1, 4],
       [1, 5],
       [2, 4],
       [2, 5],
       [3, 4],
       [3, 5]])

You want itertools.product .

In [2]: import itertools

In [3]: scipy.array(list(itertools.product([1,2,3], [4,5])))
Out[3]: 
array([[1, 4],
       [1, 5],
       [2, 4],
       [2, 5],
       [3, 4],
       [3, 5]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM