-3

If I have a Numpy array like X=np.array([1,2,3,4,5]) I want to put all of the combinations of these numbers into an array.

How would I go about getting an array with each row being a combination of X and the length is how ever many combinations there are?

  • 1
    Combinations or permutations? – ndrplz Nov 26 '19 at 15:25
  • 1
    Possible a duplicate of https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements ? – CutePoison Nov 26 '19 at 15:27
  • That question talks about doing it with lists. My question is different, I specifically want to do it with Numpy arrays and in such a way that it returns an array as described in my question. – TunTunWarrior365 Nov 26 '19 at 15:33
  • 1
    Possible duplicate of [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Arkistarvh Kltzuonstev Nov 26 '19 at 18:59

2 Answers2

1

Assuming from your question you are actually looking for permutations:

from itertools import permutations

import numpy as np

x = np.array([1, 2, 3, 4, 5])

perm_array = np.asarray([p for p in permutations(x)])
print(perm_array.shape)
# prints(120, 5)

Each row of perm_array will contain a permutation of your input.

Watch out that the number of permutations grows extremely quickly!

ndrplz
  • 1,584
  • 12
  • 16
0

Available in itertools:

from itertools import combinations
X=np.array([1,2,3,4,5])
X_combinations = {} # dictionary key r: combinations of rank r. 
for r in range(len(X) + 1): 
  X_combinations[r] = list(combinations(X, r))

from pprint import pprint
pprint(X_combinations) 

output:

{0: [()],
 1: [(1,), (2,), (3,), (4,), (5,)],
 2: [(1, 2),
     (1, 3),
     (1, 4),
     (1, 5),
     (2, 3),
     (2, 4),
     (2, 5),
     (3, 4),
     (3, 5),
     (4, 5)],
 3: [(1, 2, 3),
     (1, 2, 4),
     (1, 2, 5),
     (1, 3, 4),
     (1, 3, 5),
     (1, 4, 5),
     (2, 3, 4),
     (2, 3, 5),
     (2, 4, 5),
     (3, 4, 5)],
 4: [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)],
 5: [(1, 2, 3, 4, 5)]}
Fakher Mokadem
  • 1,059
  • 1
  • 8
  • 22