Data type conversion
Convert columns to the right type so sorting, maths and dates behave.
In this page:
Syntax
df["column"] = df["column"].astype(type)
df["column"] = pd.to_numeric(df["column"], errors="coerce")
Data type conversion
astype changes a column's dtype. pd.to_numeric with errors="coerce" turns bad values into NaN instead of failing, and pd.to_datetime parses date strings. Use the nullable "Int64" dtype to keep integers alongside missing values.
Note:
errors="coerce" is your friend for dirty data.
Example: Data type conversion
import pandas as pd
df = pd.DataFrame({"n": ["1", "2", "oops"], "d": ["2024-01-05", "2024-02-10", "2024-03-15"]})
df["n"] = pd.to_numeric(df["n"], errors="coerce")
df["d"] = pd.to_datetime(df["d"])
print(df)
print(df.dtypes)
print(df["n"].astype("Int64"))
# Output:
# n d
# 0 1.0 2024-01-05
# 1 2.0 2024-02-10
# 2 NaN 2024-03-15
# n float64
# d datetime64[ns]
# dtype: object
# 0 1
# 1 2
# 2 <NA>
# Name: n, dtype: Int64
Related Topics
Common Mistakes
- Converting a column with NaN to int
- Not using coerce on bad values
- Parsing dates in an ambiguous day/month order
Chapter Summary
- astype converts dtypes
- to_numeric coerce turns junk into NaN
- to_datetime parses dates
- Int64 allows missing integers
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: