0

Given an array

A = np.array([
    [1, 2, 3, 4],
    [10, 20, 30, 40]
])

I want to get in the vectorized way an array of k combinations, for example for k=3

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

       [[10, 20, 30],
       [10, 20, 40],
       [10, 30, 40],
       [20, 30, 40]]
])

and for k=2

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

       [[10, 20],
       [10, 30],
       [10, 40],
       [20, 30],
       [20, 40],
       [30, 40]]
])

Any ideas how to achieve that?

Sengiley
  • 221
  • 2
  • 7
  • Looks like you want to use `itertools.combinations` - separately on the 2 lists/arrays. A lot of the other answers in the duplicate are for `product`. – hpaulj Aug 20 '22 at 22:37
  • no, `itertools.combinations` will involve loops over each entry in `A` which is slow, what I want is to avoid it – Sengiley Aug 20 '22 at 22:38
  • You could try `np.array(list(combinations(A.T,k))).transpose(2,0,1)`. But a small number of iterations (e.g.2) on a complex task, is not particularly slow. But feel free to do your own timings. – hpaulj Aug 20 '22 at 22:44
  • no, it's the example which have 2 iterations, the arrays which I consider can have tens of thousands of entries along 0 axis – Sengiley Aug 20 '22 at 22:47
  • The question might still be open if you'd posted your non 'vectoruzed' way and explained what was wrong with it. – hpaulj Aug 21 '22 at 02:28

0 Answers0