Sub topic 3
Converting a column with astype
This chapter assumes you can build a DataFrame, select columns, and read dtypes with df.dtypes. You will learn to use astype, the basic tool for changing a column's dtype. You will also learn where it stops working and which tool to reach for next.
What astype does
Series.astype(dtype) returns a new Series with every value cast to the dtype you name. It does not change the original. You must assign the result back to keep it.
import pandas as pd
df = pd.DataFrame({
"qty": ["3", "5", "7"],
"score": [1.0, 2.0, 3.0],
"status": ["shipped", "pending", "shipped"],
})
df["qty"] = df["qty"].astype("int64")
print(df.dtypes)Name the dtype as a string, such as "int64". Plain int means a platform-dependent integer size on some systems, so the string is safer.
To convert several columns at once, pass a dictionary from column name to dtype. Columns not in the dictionary are left alone.
df = df.astype({"score": "float32", "status": "category"})
print(df.dtypes)astype is strict
astype has no cleaning step. If one value cannot be cast, the whole call fails.
s = pd.Series(["3", "5", "n/a"])
try:
s.astype("int64")
except ValueError as err:
print("Conversion failed:", err)A failed call raises an error and leaves your data unchanged. That is useful when you want bad data to stop the script. When you expect bad values, use pd.to_numeric or pd.to_datetime instead. Later chapters cover both.
Common gotchas
Casting floats to integers truncates the decimals and does not round.
print(pd.Series([1.9, 2.7]).astype("int64").tolist())This prints [1, 2]. Call .round() first if you want rounding.
Missing values also cause trouble. A NumPy int64 column cannot hold NaN, so this fails:
s = pd.Series([1.0, None, 3.0])
try:
s.astype("int64")
except ValueError as err:
print("Cannot convert NaN to integer")
print(s.astype("Int64"))The capital-I "Int64" is a nullable integer dtype. It stores missing values as <NA> and keeps the rest as integers.
Converting to text has a similar trap. astype(str) turns a missing value into the literal text "nan" or "None". The "string" dtype keeps it missing.
s = pd.Series(["a", None])
print(s.astype(str).tolist())
print(s.astype("string").tolist())Choosing a conversion tool
The diagram shows how to pick a tool based on how clean the column is.
Summary of useful targets
| Target dtype | Use it for | Handles missing values |
|---|---|---|
| `"int64"` | Whole numbers with no gaps | No |
| `"Int64"` | Whole numbers that may have gaps | Yes |
| `"float64"` | Decimal numbers | Yes, as `NaN` |
| `"string"` | Text | Yes, as `<NA>` |
| `"category"` | Repeated labels | Yes |
Exercise
A Series is created with pd.Series(["10", "20", "x"]). Calling .astype("int64") on it raises a ValueError. Why does it fail, and what happens to the original Series?
Show answer
astype cannot parse the text "x" as an integer, and it does not skip bad values, so the whole call raises an error. The original Series is not changed, because astype returns a new Series and the call never finished.
Exercise
A float column contains [4.0, NaN, 6.0]. Which astype target converts it to integers and keeps the missing value?
Show answer
astype("Int64"), the nullable integer dtype. The plain "int64" dtype raises an error because it cannot store NaN.