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
- A plain assignment mutates;
assigncopies. - A lambda inside
assignsees the frame as it is being built. - Several columns in one call are evaluated in order.
Keywords and builtins used here
aslambdalistprint
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.
Step 1 of 5 in Deriving columns, step 9 of 26 in pandas.