I have a series (month_addded) in my DataFrame like this:
9.0
12.0
12.0
nan
1.0
I want all the floats to be ints, and the NaN's to stay as they are. I did this:
for i in df['month_added']:
if i > 0:
i=int(i)
But it did nothing.
I have a series (month_addded) in my DataFrame like this:
9.0
12.0
12.0
nan
1.0
I want all the floats to be ints, and the NaN's to stay as they are. I did this:
for i in df['month_added']:
if i > 0:
i=int(i)
But it did nothing.
NaN is float typed, so Pandas would always downcast your column to float as long as you have NaN. You can use Nullable Integer, available from Pandas 0.24.0:
df['month_added'] = df['month_added'].astype('Int64')
If that's not possible, you can force Object type (not recommended):
df['month_added'] = pd.Series([int(x) if x > 0 else x for x in df.month_added], dtype='O')
Or since your data is positive and NaN, you can mask NaN with 0:
df['month_added'] = df['month_added'].fillna(0).astype(int)