HOWTO · Python
How to Fix ValueError: Cannot Convert Float NaN to Integer in Python
This tutorial will teach you to fix the ValueError: cannot convert float NaN to integer in Python.
On this page
A conversion such as int(value) or a pandas integer cast cannot represent NaN, which is a floating-point marker often used for missing data. The message ValueError: cannot convert float NaN to integer describes that conversion problem; pandas may instead raise pandas.errors.IntCastingNaNError, sometimes mentioning infinity as well. Choose whether to replace or remove affected values based on what they mean in your data.
Use pandas fillna() to Replace NaN Before Converting to Integer
Use fillna() when each affected row should remain and you have a meaningful replacement. Replacing a missing price with 0 is appropriate only if zero is a valid price for your application. This self-contained example compares filling a price with a chosen value, dropping rows with a missing price, and converting a NumPy scalar after replacing NaN. The shown example was verified: it prints [540, 0, 220], [540, 220], and 0.
Run this example:
import numpy as np
import pandas as pd
prices = pd.DataFrame({"item": ["A", "B", "C"], "price": [540.0, np.nan, 220.0]})
filled = prices.copy()
filled["price"] = filled["price"].fillna(0).astype(int)
remaining = prices.dropna(subset=["price"]).copy()
remaining["price"] = remaining["price"].astype(int)
scalar = int(np.nan_to_num(np.nan))
print(filled["price"].tolist())
print(remaining["price"].tolist())
print(scalar)
The first list retains every row and uses the chosen replacement; the second omits the row whose price was missing. The scalar conversion demonstrates that numpy.nan_to_num() returns a numeric scalar that can be passed to int().
Use pandas dropna() to Remove Rows With NaN Before Integer Conversion
Use dropna() when rows with missing values should be excluded from the result. By default, dropna() removes rows that contain missing values in any column, which may discard otherwise useful data. Pass subset=["price"] to base removal only on the column you plan to convert, as in the example above. Then convert that cleaned column with astype(int). Check how many rows remain if preserving records matters to your analysis.
Use numpy.nan_to_num() to Replace NaN Before Integer Conversion
For NumPy data, numpy.nan_to_num() replaces NaN with 0.0 by default; use its nan argument to choose a different replacement when needed. Convert the returned scalar with int(...), or apply the function to an array before using astype(int). Do not call .astype() on the scalar returned by numpy.nan_to_num(numpy.nan), because it is not an array. If the data also contains positive or negative infinity, handle those values explicitly: replacing NaN alone does not make infinity safe for integer conversion. In pandas, inspect the affected column for both missing and non-finite values before choosing a cleanup rule.