Skip to main content
Albero Academy

Fixing Data Types

Convert columns to the right dtype — numbers, dates and categories.

Cleaning & Transforming9 min

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

to the right type
df["package"] = pd.to_numeric(df["package"], errors="coerce") # bad → NaN
df["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:

datetime parts
df["year"] = df["enrolled"].dt.year
df["month"] = df["enrolled"].dt.month_name()
df["weekday"] = df["enrolled"].dt.day_name()

Key takeaways

  1. 01to_numeric / to_datetime / astype fix the two most common data bugs (numbers-as-text, dates-as-strings).
  2. 02errors="coerce" turns unparseable values into NaN rather than raising.
  3. 03After to_datetime, the .dt accessor exposes year/month/day/weekday.
  4. 04astype("category") saves memory on columns of repeated strings.

Finished this chapter?

Mark it complete to track your progress through Pandas.