Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe add integer columns into datetime columns

I have a column named transaction_date which stores date, 1970-01-01 for example, and payment_plan_days stores the amount of days, 30, 70, any integer.

How should I add payment_plan_days into transaction_date to create a new column as membership_expire_date ?

I had tried with code below and it doesn't work since they are not the same dtype.

df_transactions.loc[(df_transactions['membership_expire_date'] == '19700101'), 'membership_expire_date'] = 
    df_transactions.loc[(df_transactions['membership_expire_date'] == '19700101'), 'transaction_date'] 
    + df_transactions.loc[(df_transactions['membership_expire_date'] == '19700101'), 'payment_plan_days']
like image 356
Mervyn Lee Avatar asked Oct 24 '17 10:10

Mervyn Lee


1 Answers

I think you need to_timedelta:

df['new'] = df['transaction_date'] + pd.to_timedelta(df['payment_plan_days'], unit='d')

Sample:

dates=pd.to_datetime(['1970-01-01','2005-07-17', '2005-07-17'])
df = pd.DataFrame({'transaction_date':dates, 'payment_plan_days':[30,70,100]})

df['new'] = df['transaction_date'] + pd.to_timedelta(df['payment_plan_days'], unit='d')
print (df)
   payment_plan_days transaction_date        new
0                 30       1970-01-01 1970-01-31
1                 70       2005-07-17 2005-09-25
2                100       2005-07-17 2005-10-25
like image 63
jezrael Avatar answered Oct 21 '22 07:10

jezrael