查找所有可能的箱柜组合

时间:2015-07-02 09:42:36

标签: python combinations slice binning

我在19-80的范围内有一个变量age的100.000观测值。我想根据X变量找到age个bin。 bin范围不得重叠,并且应该跨越整个间隔。例如,使用X = 4一个可能的bin组合可以是:

  • 18-30
  • 31-45
  • 46-57
  • 58-80

如何在给定值X的情况下找到所有可能的bin组合?

编辑: @Wolf提示,这是我想要实现自己的另一个约束。每个bin必须至少包含age变量的10个值。这当然会限制X X <= 6

我试图通过@ mkrieger1将其整合到答案中,但失败了。

def bin_combinations(values, n):
    """
    Generate all possible combinations of splitting the values into n
    contiguous parts.

    >>> list(bin_combinations('abcd', 3))
    [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]
    """

    for indices in combinations(range(1, len(values)), n - 1):
        li = list(indices)
        starts = [None] + li
        ends = li + [None]
        size = li[-1] - li[0]
        if size >= 10:
            yield [values[start:end] for start, end in zip(starts, ends)]

1 个答案:

答案 0 :(得分:1)

最合适的是,您可以使用itertools标准库模块中的combinations函数找到组合。

from itertools import combinations

def bin_combinations(values, n):
    """
    Generate all possible combinations of splitting the values into n
    contiguous parts.

    >>> list(bin_combinations('abcd', 3))
    [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]
    """
    for indices in combinations(range(1, len(values)), n - 1):
        starts = [None] + list(indices)
        ends = list(indices) + [None]
        yield [values[start:end] for start, end in zip(starts, ends)]
相关问题