String and Date Operations in pandas
Transform text and date columns at scale — the most-used pandas preprocessing operations
After loading data, the two column types that need the most work are strings (text) and dates. pandas has a .str accessor for string operations and a .dt accessor for datetime operations — letting you apply transformations to an entire column in one line.
Examples
Key Points
- ✓.str accessor enables string methods on an entire column — no loop needed
- ✓.dt accessor enables datetime methods — requires pd.to_datetime() first
- ✓str.contains(na=False) avoids errors when NaN values exist in the column
- ✓strftime format codes: %Y=4-digit year, %m=month number, %B=month name, %d=day
- ✓Date arithmetic with pd.Timestamp.today() gives age in days for each row
Practice Question
After pd.to_datetime(), how do you extract just the year from a date column "OrderDate"?