typestar

Adding columns in Python

assign returns a new frame, which is what makes chaining safe.

import pandas as pd

frame = pd.DataFrame({"chars": [420, 380], "seconds": [60.0, 45.0]})

wider = frame.assign(
    cps=lambda f: f["chars"] / f["seconds"],
    wpm=lambda f: (f["cps"] * 60 / 5).round(1),
    fast=lambda f: f["wpm"] > 80,
)

print(wider)
print(list(frame.columns))  # untouched

How it works

  1. A plain assignment mutates; assign copies.
  2. A lambda inside assign sees the frame as it is being built.
  3. Several columns in one call are evaluated in order.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
283
Tokens
109
Three-star pace
105 tpm

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

Type this snippet

Step 1 of 5 in Deriving columns, step 9 of 26 in pandas.

← Previous Next →