I\'m creating this array:
A=itertools.combinations(range(6),2)
and I have to manipulate this array with numpy, like:
A.resh
An alternative way to get every pairwise combination of N
elements is to generate the indices of the upper triangle of an (N, N)
matrix using np.triu_indices(N, k=1)
, e.g.:
np.vstack(np.triu_indices(6, k=1)).T
For small arrays, itertools.combinations
is going to win, but for large N the triu_indices
trick can be substantially quicker:
In [1]: %timeit np.fromiter(itertools.chain.from_iterable(itertools.combinations(range(6), 2)), np.int)
The slowest run took 10.46 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 4.04 µs per loop
In [2]: %timeit np.array(np.triu_indices(6, 1)).T
The slowest run took 10.97 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 22.3 µs per loop
In [3]: %timeit np.fromiter(itertools.chain.from_iterable(itertools.combinations(range(1000), 2)), np.int)
10 loops, best of 3: 69.7 ms per loop
In [4]: %timeit np.array(np.triu_indices(1000, 1)).T
100 loops, best of 3: 10.6 ms per loop