apply, map and vectorizing in Python
apply is a loop wearing a nice hat: reach for a vectorized expression first.
import pandas as pd
frame = pd.DataFrame({"chars": [420, 380], "errors": [3, 0]})
print(frame["chars"].map(lambda n: n // 5))
print(frame.apply(lambda col: col.max() - col.min()))
print(frame.apply(lambda row: row["chars"] - row["errors"], axis=1))
# the same thing, vectorized
print((frame["chars"] - frame["errors"]).tolist())
How it works
Series.mapapplies elementwise,DataFrame.applyper column or row.axis=1walks rows, which is the slow direction.- Arithmetic on whole columns is what pandas is fast at.
Keywords and builtins used here
aslambdaprint
The run, in numbers
- Lines
- 10
- Characters to type
- 331
- Tokens
- 125
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 71 seconds.
Step 2 of 5 in Deriving columns, step 10 of 26 in pandas.