Skip to the workspace
Pebellslearn by building
Cleaning Data  ›  Capstone Project

Fixing Types and Parsing Dates

Casting Types 15 minEach column should hold the type that matches its meaning, using astype or to_numeric for numbers, to_datetime and the dt accessor for dates, and category for repeated labels.

python data analysis / Fixing Types and Parsing Dates

Explore each scene at your own pace.

01 · The rule

The rule

Fixing Types and Parsing Dates

The owner asks, "Do we sell more at weekends?" But the date column is plain text like "2024-03-02", and text has no idea what a Saturday is. Worse, a copies column loaded as text will "add" 3 and 5 into "35". Every column needs the type that matches its meaning before the analysis can be trusted.

The rule

Give each column the type of its meaning: numbers, dates, or categories.

Numbers. astype converts when every value is clean; to_numeric copes when some are not:

s = pd.Series(["3", "5", "2"])
s.sum()                     # '352', text glued together
s.astype(int).sum()         # 10

bad = pd.Series(["3", "5", "two"])
bad.astype(int)                           # ValueError
pd.to_numeric(bad, errors="coerce")       # 3.0, 5.0, NaN

errors="coerce" turns anything unreadable into NaN, which you then handle like any other missing value.

Dates. pd.to_datetime turns text into real timestamps, and the .dt accessor unlocks their parts:

sales["date"] = pd.to_datetime(sales["date"])
sales["date"].dt.day_name()     # Friday, Friday, Saturday, Saturday, Sunday, …
sales["date"].dt.month          # 3 for every row
sales["date"].max() - sales["date"].min()   # 3 days

Ambiguous text is a real danger: "03/04/2024" is read month first, as 4 March. For Indian-style day-first dates, pass dayfirst=True to get 3 April, or better, give an exact format="%d/%m/%Y".

Categories. A text column with a few repeating values, like genre, can become the category type, which stores each label once and saves memory:

sales["genre"] = sales["genre"].astype("category")
sales["genre"].cat.categories    # comics, fiction, science
pd.get_dummies(sales["genre"])    # one True/False column per genre

get_dummies is how categories are turned into numbers for models: three genres become three yes/no columns.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.