1

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.

Vasilis
  • 143
  • 10
  • 1
    Does this answer your question? [How can I check for NaN values?](https://stackoverflow.com/questions/944700/how-can-i-check-for-nan-values) – Bizhan Dec 03 '19 at 11:09

1 Answers1

1

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')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252