typestar

Method chaining with pipe in Python

pipe puts your own function in a chain, so the whole transform reads top to bottom.

import pandas as pd


def add_wpm(frame, chars_per_word=5):
    return frame.assign(
        wpm=(frame["chars"] / chars_per_word / (frame["seconds"] / 60)))


def only_fast(frame, floor=70):
    return frame[frame["wpm"] >= floor]


runs = pd.DataFrame({"chars": [420, 200, 610], "seconds": [60.0, 60.0, 60.0]})

result = (runs
          .pipe(add_wpm)
          .pipe(only_fast, floor=50)
          .sort_values("wpm", ascending=False)
          .round(1))
print(result)

How it works

  1. Each step takes a frame and returns a frame.
  2. No intermediate variables means no stale ones.
  3. pipe passes extra arguments through to your function.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
416
Tokens
137
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 3 of 5 in Deriving columns, step 11 of 26 in pandas.

← Previous Next →