How can I solve the issue 'ValueError: cannot convert float NaN to integer' in python
Question:
Following is the code part that the above issue appeared.
df["Height (cm)"]= df["Height (cm)"].astype(int)
The Dtype of "Height (cm)" was initially ‘object’ and the missing values of it were replaced with np.nan.
Then I tried to execute the above code to convert Height into an integer type, but ended up by having the error ‘ValueError: cannot convert float NaN to integer’.
How can I solve this issue?
Answers:
You need to say what you want to do with nans. You can either drop those rows (df.dropna()
) or replace nans with something else (0
for instance: df.fillna(0)
)
df["Height (cm)"]= df["Height (cm)"].fillna(0).astype(int)
Use Int64
instead
df["Height (cm)"]= df["Height (cm)"].astype('Int64')
It can handle NaN values.
Following is the code part that the above issue appeared.
df["Height (cm)"]= df["Height (cm)"].astype(int)
The Dtype of "Height (cm)" was initially ‘object’ and the missing values of it were replaced with np.nan.
Then I tried to execute the above code to convert Height into an integer type, but ended up by having the error ‘ValueError: cannot convert float NaN to integer’.
How can I solve this issue?
You need to say what you want to do with nans. You can either drop those rows (df.dropna()
) or replace nans with something else (0
for instance: df.fillna(0)
)
df["Height (cm)"]= df["Height (cm)"].fillna(0).astype(int)
Use Int64
instead
df["Height (cm)"]= df["Height (cm)"].astype('Int64')
It can handle NaN values.