def make_phases(df, predicate, name='phase'):
    """
    Insert a column 'phase' based on given predicate.
    Consecutive rows which satisfy given predicate are numbered.
    Example:
        predicate   : lambda(n): iseven(n)
        input       : 1 2 3 4 2 6 5 1 9 2 2
        output phase: 0 1 0 2 2 2 0 0 0 3 3
    """
    # helper to keep track of current phase
    class f:
        def __init__(self):
            self.phase = 0
            self.current = False
        def __call__(self, row):
            p = predicate(row)
            if p:
                if self.current:
                    return self.phase
                else:
                    self.current = True
                    self.phase += 1
                return self.phase
            self.current = False
            return 0
    df['phase'] = df.apply(f(), axis=1)