Cast the column to Pandas’ nullable integer dtype "Int64" (capital "I", e.g., df["col"] = df["col"].astype("Int64"))—or pd.to_numeric(..., errors="coerce").astype("Int64") when strings or messy values are present—because standard NumPy "int64" (lowercase "i") cannot represent NaN and raises pd.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer, whereas "Int64" preserves missing entries natively as pd.NA.
Basic Example
import numpy as np
import pandas as pd
df = pd.DataFrame({
"user_id": [101.0, 102.0, np.nan, 104.0],
"age": [25.0, np.nan, 31.0, 40.0],
"score": [88.7, 92.3, np.nan, 79.9],
})
# Standard `df["user_id"].astype("int64")` fails with:
# pd.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer
# 1. Recommended: Cast to Pandas nullable integer `"Int64"` (capital "I") to keep `pd.NA`
df["user_id"] = df["user_id"].astype("Int64")
print(df["user_id"])
# Output:
# 0 101
# 1 102
# 2 <NA>
# 3 104
# Name: user_id, dtype: Int64
# 2. If you want a standard NumPy `int64` column with a sentinel fallback instead of `<NA>`:
df["age_filled"] = df["age"].fillna(-1).astype("int64")
# 3. Round non-whole floats before casting to `"Int64"` (`.astype("Int64")` truncates toward zero):
df["score_rounded"] = df["score"].round().astype("Int64")
print(df[["user_id", "age_filled", "score_rounded"]])
Key Details & Edge Cases
- Capital
"Int64"vs. lowercase"int64"(and sized variants"Int8","Int16","Int32","UInt64"):- Lowercase
"int64"is a fixed-width NumPy integer dtype that has no bit pattern forNaN, crashing immediately onNaNorinf. - Capital
"Int64"(and"Int32","Int16","Int8") is a Pandas extension dtype backed by a separate boolean validity mask, allowing true integer values to coexist withpd.NA.
- Lowercase
- Non-whole decimals raise
TypeErrorin modern Pandas (TypeError: Cannot safely cast non-equivalent float64 to int64):- Calling
.astype("Int64")on a float column containing fractional values like[1.2, 2.5, np.nan]raisesTypeError: Cannot safely cast non-equivalent float64 to int64in Pandas 2.x+. Explicitly call.round(),np.floor(), ornp.ceil()before.astype("Int64")when floats have non-zero decimals.
- Calling
- Infinite values (
np.inf/-np.inf) still fail.astype("Int64"):- Nullable
"Int64"representspd.NA, not IEEE 754 infinity (inf). Replace infinities first viadf["col"].replace([np.inf, -np.inf], np.nan).astype("Int64")if division-by-zero values may exist.
- Nullable
- Converting multiple float columns at once (
df.convert_dtypes()or dictionaryastype):- Convert specific columns in bulk with
df = df.astype({"user_id": "Int64", "age": "Int64"}), or calldf = df.convert_dtypes()to automatically convert all whole-number float columns (plus strings and booleans) across the entire DataFrame into Pandas nullable dtypes (Int64,string,boolean).
- Convert specific columns in bulk with
- Exporting
"Int64"columns cleanly to CSV or JSON:.to_csv()writespd.NAas an empty field ("") without.0decimals (101,102,,104), fixing the classic Pandas float-ID.0export artifact.
Comparison of Float-to-Integer Conversion Methods with NaNs in Pandas
| Method | Preserves Missing Values (NaN $\rightarrow$ pd.NA)? |
Resulting Dtype | Handles Fractional Floats (1.7)? |
Best Used When |
|---|---|---|---|---|
s.astype("Int64") (Recommended) |
Yes (pd.NA) |
Int64 (Pandas nullable integer) |
No (whole floats like 1.0 only; chain .round() first for 1.7) |
Converting IDs, counts, ages, or codes with missing values while preserving true nulls. |
s.round().astype("Int64") |
Yes (pd.NA) |
Int64 (Pandas nullable integer) |
Yes (rounds to nearest even integer) | Converting continuous float measurements or scores with NaNs into rounded integers. |
s.fillna(0).astype("int64") |
No (replaces NaN with 0 or -1) |
int64 (standard NumPy integer) |
Yes (truncates toward zero) | Downstream C/NumPy/scikit-learn APIs that require strict non-nullable NumPy int64 arrays. |
df.convert_dtypes() |
Yes (pd.NA) |
Int64 / Int32 (auto-inferred) |
No (leaves non-whole floats as Float64) |
Automatically upgrading an entire DataFrame’s whole-number float columns to nullable integers. |
You must log in or register to comment.
