22/34
Part 6 of 8 · BandsLearn and do

groupby splits the steps into runs, and only the row-local runs go on bands

Some steps can run on bands and some can't, so split the step list where that changes.

from itertools import groupby

ROW_LOCAL = {"scale", "clip", "map"}


def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32


steps = [("clip", 0, 40), ("map", to_fahrenheit), ("sort", 1), ("scale", 10), ("head", 3)]
for local, run_of_steps in groupby(steps, key=lambda step: step[0] in ROW_LOCAL):
    print(local, [step[0] for step in run_of_steps])
True ['clip', 'map']
False ['sort']
True ['scale']
False ['head']

A run here is a stretch of consecutive steps of the same kind. itertools.groupby starts a new group each time the key changes, and the key is whether a step is row-local. Each True run goes on bands. Each False run goes on the whole table, stitched together first:

The steps split into runsInteractive
T, 5 x 3.

Grouping runs, not single steps, means clip then map cut and stitch once, not twice. Don't sort the steps first, as the usual groupby recipe does: the order of the steps is the meaning of the pipeline.

Put together, with the bands on a thread pool, in_bands on T in bands of 2 with these steps returned [[770.0, 320.0, 752.0], [680.0, 644.0, 698.0], [698.0, 662.0, 734.0]]. That's the same as apply.

In the editor, write runs(steps, row_local): the groupby loop above, returned as a list of (local, names) pairs.