Generate pair wise column combination from np.array

Viewed 188

I have an np.array of size 500 x 15. How can I generate a new np array with all possible pair-wise combination of 2 columns from this array?

arr = [ [col1],[col2],[col3],..., [col14]]

I want output such that it generates combination as

 [[col1],[col2]]
 [[col1],[col3]]
 .
 .
 [[col13],[col14]]

I can't find a way to select all column values in the output. For an array having 15 columns there should be N*(N-1) i.e. 15 * 14 = 210 pairs.

1 Answers

You can use combinations from itertools to select all unique pair of columns.

from itertools import combinations

np.random.seed(0)

arr = np.array(np.random.randn(2, 3))
>>> arr
array([[ 1.76405235,  0.40015721,  0.97873798],
       [ 2.2408932 ,  1.86755799, -0.97727788]])

>>> np.array([arr[:, [i, j]] for i, j in combinations(range(arr.shape[1]), 2)])
array([[[ 1.76405235,  0.40015721],  # First and second column.
        [ 2.2408932 ,  1.86755799]],

       [[ 1.76405235,  0.97873798],  # First and third column.
        [ 2.2408932 , -0.97727788]],

       [[ 0.40015721,  0.97873798],  # Second and third column.
        [ 1.86755799, -0.97727788]]])
Related