The .str accessor in Python
Vectorized string methods, with the same names as Python's own.
import pandas as pd
files = pd.Series(["python/pd_strings.py", "rust/rs_traits.rs",
"sql/select_where.sql"])
print(files.str.split("/").str[0].tolist())
print(files.str.upper().str.endswith(".PY").tolist())
print(files.str.extract(r"([a-z]+)/(\w+)\.")[1].tolist())
print(files[files.str.contains("traits")].tolist())
How it works
.strmaps over the column without a loop.extractpulls capture groups into columns.containsreturns a boolean mask for filtering.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 9
- Characters to type
- 318
- Tokens
- 114
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 65 seconds.
Step 4 of 5 in Deriving columns, step 12 of 26 in pandas.