-1

The itertools.combinations produce the following result on 1d array:

array = [1,2,3]
list(itertools.combinations(array, 2))
>>>[(1, 2), (1, 3), (2, 3)]

This is great but what if I want to apply this to every row of a 2d vector?

array = [
           [1,2,3],
           [1,2,3]
        ]
list(itertools.combinations(array, 2))
>>>[(array([1, 2, 3]), array([1, 2, 3]))]

The above just combines two sub arrays but what I really want is this:

>>>[
        [(1, 2), (1, 3), (2, 3)],
        [(1, 2), (1, 3), (2, 3)]
   ]
Anonymous
  • 4,692
  • 8
  • 61
  • 91
  • "what if I want to apply this to every row" Then you apply this to every row. – Pychopath Feb 19 '22 at 03:19
  • it is easy to just loop on every row but I want a vectorized solution – Anonymous Feb 19 '22 at 03:22
  • 1
    Define "vectorized". – Pychopath Feb 19 '22 at 03:24
  • 1
    For the record: 1) Someone else downvoted your question, wasn't me. 2) You show regular Python lists and only tagged this as a Python question, not NumPy or so. And I'm not aware of vectorization like NumPy's in just Python, so if you want "vectorized" in just Python, you do need to be clear about what you'd consider vectorized. Maybe a `map` usage? I really don't think my request for clarification about this warranted your "define your mother" response. – Pychopath Feb 19 '22 at 03:53

1 Answers1

0

Edit: I was thinking in terms of code before I articulated my answer.

Essentially we just permute the column indices then use them to select the actual array values by broadcasting them to every row of the matrix.

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

index = list(itertools.combinations(range(array.shape[-1]), 2))

print(array[:, index])
Anonymous
  • 4,692
  • 8
  • 61
  • 91
  • 1: code only answers are dicouraged. 2. it's not clear why you need `vstack`. Won't numpy broadcasting work without it? – Mark Feb 19 '22 at 03:57
  • Just thought I might stack those tuples, good point it works even without it. – Anonymous Feb 19 '22 at 03:59