typestar

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

  1. .str maps over the column without a loop.
  2. extract pulls capture groups into columns.
  3. contains returns a boolean mask for filtering.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 5 in Deriving columns, step 12 of 26 in pandas.

← Previous Next →