N-D version of itertools.combinations in numpy

You can use itertools.combinations() to create the index array, and then use NumPy’s fancy indexing: import numpy as np from itertools import combinations, chain from scipy.special import comb def comb_index(n, k): count = comb(n, k, exact=True) index = np.fromiter(chain.from_iterable(combinations(range(n), k)), int, count=count*k) return index.reshape(-1, k) data = np.array([[1,2,3,4,5],[10,11,12,13,14]]) idx = comb_index(5, 3) print(data[:, idx]) output: … Read more

itertools product speed up

The NumPy equivalent of itertools.product() is numpy.indices(), but it will only get you the product of ranges of the form 0,…,k-1: numpy.rollaxis(numpy.indices((2, 3, 3)), 0, 4) array([[[[0, 0, 0], [0, 0, 1], [0, 0, 2]], [[0, 1, 0], [0, 1, 1], [0, 1, 2]], [[0, 2, 0], [0, 2, 1], [0, 2, 2]]], [[[1, 0, … Read more

permutations with unique values

Because sometimes new questions are marked as duplicates and their authors are referred to this question it may be important to mention that sympy has an iterator for this purpose. >>> from sympy.utilities.iterables import multiset_permutations >>> list(multiset_permutations([1,1,1])) [[1, 1, 1]] >>> list(multiset_permutations([1,1,2])) [[1, 1, 2], [1, 2, 1], [2, 1, 1]]

How do I use itertools.groupby()?

IMPORTANT NOTE: You have to sort your data first. The part I didn’t get is that in the example construction groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) k is the current grouping key, and g is an iterator that you can … Read more