Numbers read as text and dates read as strings are the two most common data bugs. Fixing dtypes explicitly unlocks the right operations — maths on numbers, .dt accessors on dates, memory savings on categories.
Type conversion
df["package"] = pd.to_numeric(df["package"], errors="coerce") # bad → NaNdf["enrolled"] = pd.to_datetime(df["enrolled"])df["programme"] = df["programme"].astype("category") # saves memory
The .dt and .cat accessors
Once a column is the right type, specialised accessors open up:
df["year"] = df["enrolled"].dt.yeardf["month"] = df["enrolled"].dt.month_name()df["weekday"] = df["enrolled"].dt.day_name()
Key takeaways
- 01to_numeric / to_datetime / astype fix the two most common data bugs (numbers-as-text, dates-as-strings).
- 02errors="coerce" turns unparseable values into NaN rather than raising.
- 03After to_datetime, the .dt accessor exposes year/month/day/weekday.
- 04astype("category") saves memory on columns of repeated strings.
