简体   繁体   中英

The error is the following: ValueError: cannot convert float NaN to integer

I have a column with datetime64[ns] values. So, in some cells in pandas, it has the value NaN when it is blank. I want to run the following function, but I am facing an error.

The error is the following:ValueError: cannot convert float NaN to integer

Here is the function I have:

def excel_date2(date1):
    temp = datetime(1899, 12, 30)   
    delta = date1 - temp
    return int(delta.days)

Here is where I am calling it in my project:

df['endedAtInteger'] = df['endedAt'].apply(excel_date2)

Here is an example of values the column has:

NaN

2018-09-02 15:20:15

2018-09-02 18:04:34

2018-09-02 18:11:15

2018-09-02 18:39:34

However, I do not want to permanently change the type of values of that column so in whatever you recommend please do it to another column. And I do not want to remove those values if possible.

I think converting to integers here is not necessary, if missing values all data are casted to floats:

def excel_date2(date1):
    temp = datetime(1899, 12, 30)   
    delta = date1 - temp
    return delta.days

But if need it is possible use Nullable integer data type :

df['endedAtInteger'] = df['endedAt'].apply(excel_date2).astype('Int64')

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