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?

Asked By: RoshiDil

||

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)
Answered By: ted

Use Int64 instead

df["Height (cm)"]= df["Height (cm)"].astype('Int64')

It can handle NaN values.

Answered By: korakot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.