I'm trying to convert float numbers to int in my df column with this one liner:
df['id'] = df['id'].map(lambda x: int(x))
But some values are NaN an will throw:
ValueError: cannot convert float NaN to integer
How do I fix this?
You can use the fillna() function to replace NaN values in a pandas DataFrame.
To convert a column that includes a mixture of float and NaN values to int, first replace NaN values with zero on pandas DataFrame and then use astype() to convert. Use DataFrame. fillna() to replace the NaN values with integer value zero. Yields below output.
You can replace all values or selected values in a column of pandas DataFrame based on condition by using DataFrame. loc[] , np. where() and DataFrame. mask() methods.
NaN is itself float and can't be convert to usual int. You can use pd.Int64Dtype() for nullable integers:
# sample data:
df = pd.DataFrame({'id':[1, np.nan]})
df['id'] = df['id'].astype(pd.Int64Dtype())
Output:
id
0 1
1 <NA>
Another option, is use apply, but then the dtype of the column will be object rather than numeric/int:
df['id'] = df['id'].apply(lambda x: x if np.isnan(x) else int(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With