How to fix OverflowError: Overflow in int64 addition

拈花ヽ惹草 提交于 2020-02-02 13:13:27

问题


I'm trying to subtract column df['date_of_admission'] from the column df['DOB'] to find the difference between then and store the age value in df['age'] column, however, I'm getting this error:

OverflowError: Overflow in int64 addition

 DOB          date_of_admission      age
 2000-05-07   2019-01-19 12:26:00        
 1965-01-30   2019-03-21 02:23:12        
 NaT          2018-11-02 18:30:10        
 1981-05-01   2019-05-08 12:26:00       
 1957-01-10   2018-12-31 04:01:15         
 1968-07-14   2019-01-28 15:05:09            
 NaT          2018-04-13 06:20:01 
 NaT          2019-02-15 01:01:57 
 2001-02-10   2019-03-21 08:22:00       
 1990-03-29   2018-11-29 03:05:03
.....         ......
.....         .....
.....         .....

I've tried it with the following:

import numpy as np
import pandas as pd
from datetime import dt

df['age'] = (df['date_of_admission'] - df['DOB']).dt.days // 365

Expected to get the following age column after finding the difference between:

age
26
69
NaN
58
.
.
.

回答1:


Convert both columns into date then subtract it

import pandas as pd


df['date_of_admission'] = pd.to_datetime(df['date_of_admission']).dt.date

df['DOB'] = pd.to_datetime(df['DOB']).dt.date

df['age'] = ((df['date_of_admission']-df['DOB']).dt.days) //365

SECOND TEST

#Now I have use DOB AND date_of_admission data from the question and it is working fine

df = pd.DataFrame(data={"DOB":['2000-05-07','1965-01-30','NaT'],
                   "date_of_admission":["2019-01-19 12:26:00","2019-03-21 02:23:12", "2018-11-02 18:30:10"]})

df['DOB'] = pd.to_datetime(df['DOB']).dt.date
df['date_of_admission'] = pd.to_datetime(df['date_of_admission']).dt.date
df['age'] = ((df['date_of_admission']-df['DOB']).dt.days) //365

RESULT:

DOB       date_of_admission   age
2000-05-07  2019-01-19       18.0
1965-01-30  2019-03-21       54.0
NaT         2018-11-02       NaN



回答2:


1). You are doing it correctly but the DOB contains the only date AND date_of_admission contains both date and time. Manipulate the date_of_admission so that it will only contain the date, then you will get your result.

2). Here I am adding a change function into your code so that you will get your result.

import numpy as np
import pandas as pd
from datetime import dt

def change(x):
    return x.date()

df['date_of_admission'] = df['date_of_admission'].apply(change)

df['age'] = df['date_of_admission'].subtract(df['DOB']).dt.days // 365

I hope it will help you.



来源:https://stackoverflow.com/questions/56720783/how-to-fix-overflowerror-overflow-in-int64-addition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!