简体   繁体   中英

Convert pandas series to int with NaN values

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM