Why dtype conversion matters
Many datasets arrive with wrong dtypes:
- numbers stored as strings
- dates stored as strings
- categories stored inconsistently
If dtypes are wrong, your stats and charts can be wrong.
Convert to numeric safely
import pandas as pd
df = pd.DataFrame({"amount": ["1,200", "500", "oops", " 700 "]})
df["amount"] = df["amount"].astype(str).str.replace(",", "", regex=False).str.strip()
df["amount"] = pd.to_numeric(df["amount"], errors="coerce")
print(df)
print(df.isna().sum())Convert to datetime
import pandas as pd
df = pd.DataFrame({"date": ["2025-01-01", "2025/01/02", "invalid"]})
df["date"] = pd.to_datetime(df["date"], errors="coerce")
print(df)Categories
import pandas as pd
df = pd.DataFrame({"city": ["Pune", "Delhi", "Pune"]})
df["city"] = df["city"].astype("category")
print(df.dtypes)Validate assumptions
Typical checks:
- ID columns contain no duplicates
- numeric columns are non-negative
- date columns are within expected range
# no duplicate ids
# assert df["id"].is_unique
# non-negative values
# assert (df["amount"] >= 0).all()
# date range
# assert df["date"].min() >= pd.Timestamp("2020-01-01")Tip
Convert + validate early. It prevents subtle bugs later.
Visualize it
Each column starts life as text (or a mixed bag of types) and needs to be routed to the right converter before it's safe to use.
flowchart LR
A["Raw column (strings)"] --> B{"What kind of value?"}
B -->|"numbers"| C["pd.to_numeric(errors='coerce')"]
B -->|"dates"| D["pd.to_datetime(errors='coerce')"]
B -->|"repeated labels"| E["astype('category')"]
C --> F["Validated, typed column"]
D --> F
E --> F
๐งช Try It Yourself
Exercise 1 โ Convert text to numbers safely
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 โ Convert a column to category
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 โ Use a nullable integer dtype
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Check your understanding
For amounts "1,200", "500", "oops" and " 700 ", how many NaN values result after cleaning and to_numeric(errors="coerce")?
The commas and spaces are removed so 1,200 and 700 convert fine. Only oops cannot be parsed and becomes NaN.
Show answer
A โ 1 โ The commas and spaces are removed so 1,200 and 700 convert fine. Only oops cannot be parsed and becomes NaN.
Which line checks that an ID column has no duplicates?
is_unique is True when no value repeats. The lesson also checks non-negative amounts and date ranges.
Show answer
A โ assert df["id"].is_unique โ is_unique is True when no value repeats. The lesson also checks non-negative amounts and date ranges.
Which call converts a text column of repeated cities to a categorical dtype?
astype("category") makes the column categorical, as the dtypes printout shows.
Show answer
A โ df["city"].astype("category") โ astype("category") makes the column categorical, as the dtypes printout shows.
Why does the lesson say to convert and validate early?
If dtypes are wrong, your numbers and plots can be wrong without warning.
Show answer
A โ Wrong dtypes make stats and charts wrong, and early checks prevent subtle bugs โ If dtypes are wrong, your numbers and plots can be wrong without warning.
Next
With clean dtypes in hand, you're ready to hunt for extreme values โ see Outlier Detection (IQR Method) and Handling Outliers.