Reputation: 10033
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?
Upvotes: 7
Views: 6091
Reputation: 150735
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))
Upvotes: 10