Sub topic 7
Vectorised strings and dates with .str and .dt
This chapter assumes you can build a DataFrame, select columns, and write a basic Python loop. It also assumes you have seen column arithmetic in pandas. Here you apply the same whole-column idea to text and dates.
Why strings and dates need accessors
Arithmetic works directly on a column because df["price"] * df["qty"] is defined for numbers. Text and dates need their own methods. A plain Series has no .strip() or .month. Pandas groups those methods under two accessors:
.strholds string methods such asstrip,lower,title,contains,replaceandsplit..dtholds date and time parts such asyear,month,day,dayofweekandhour.
Each accessor call takes the whole column and returns a new Series with the same index. That means you can write df["name"].str.strip() where a loop would call strip() on one value at a time.
Cleaning text with .str
The next example cleans a name column and extracts a month in one pass.
import pandas as pd
events = pd.DataFrame({
"name": [" Ann ", "bob"],
"when": ["2026-01-05", "2026-02-10"],
})
events["name_clean"] = events["name"].str.strip().str.title()
events["month"] = pd.to_datetime(events["when"]).dt.month
print(events)The .str methods chain, so strip() runs first and title() runs on its result. The loop version would do the same two steps for each row and build a list by hand.
Common .str tools for loop replacement:
| Task | Loop habit | Vectorised form |
|---|---|---|
| Remove whitespace | `s.strip()` per value | `col.str.strip()` |
| Test for a substring | `"x" in s` per value | `col.str.contains("x")` |
| Split into parts | `s.split(",")` per value | `col.str.split(",", expand=True)` |
| Replace text | `s.replace(a, b)` per value | `col.str.replace(a, b, regex=False)` |
str.contains returns a boolean Series. You can use it as a mask, as shown in the earlier chapter on boolean masks: df[df["name"].str.contains("an", case=False)].
Working with dates using .dt
The .dt accessor works only on columns with a datetime dtype. A column of strings such as "2026-01-05" has the object dtype, so .dt raises an AttributeError. Convert it first with pd.to_datetime.
events["when_dt"] = pd.to_datetime(events["when"])
events["weekday"] = events["when_dt"].dt.day_name()
events["is_weekend"] = events["when_dt"].dt.dayofweek >= 5
events["days_since"] = (pd.Timestamp("2026-03-01") - events["when_dt"]).dt.daysSubtracting two datetimes gives a timedelta column. A timedelta column has its own .dt properties, such as .dt.days. Converting once and storing the result also avoids parsing the same strings again on every later step.
Common errors
AttributeError: Can only use .str accessor with string values. The column holds numbers or other non-strings. Convert it with.astype(str)if that is what you intend.AttributeError: Can only use .dt accessor with datetimelike values. The column is still text. Callpd.to_datetimefirst.- Missing values.
.strmethods returnNaNfor missing entries, andstr.containsreturnsNaNin the mask. Passna=Falseto get a usable mask:col.str.contains("x", na=False). - Regex surprises.
str.replacetreats the pattern as a regular expression only if you ask for it withregex=True. Setregex=Falsewhen you mean plain text. - Unparseable dates.
pd.to_datetime(col, errors="coerce")turns bad values intoNaTinstead of raising an error. Check how many you get with.isna().sum().
Speed expectations
Be realistic about the gain. .str methods still call Python string functions on each element internally, so they are not as fast as numeric column arithmetic. They are still shorter, handle missing values, and avoid building a Series per row. The .dt accessor is different. Once the column is a datetime dtype, its values are stored as integers, and .dt properties are computed in compiled code, which is much faster.
Exercise
A column signup holds strings like "2026-03-14". Write the expression that adds a boolean column is_march and explain why df["signup"].dt.month fails on the raw column.
Show answer
Use df["is_march"] = pd.to_datetime(df["signup"]).dt.month == 3. The raw column has the object dtype, and .dt works only on datetime values, so you must convert with pd.to_datetime first.
Exercise
A city column contains some missing values. How do you select rows whose city contains "york" regardless of case, without the mask causing an error?
Show answer
Use df[df["city"].str.contains("york", case=False, na=False)]. The na=False argument turns missing values into False, so the result is a clean boolean mask.