Pandas数据框将整数列添加到datetime列

时间:2017-10-24 10:12:13

标签: python pandas dataframe

我有一个名为transaction_date的列存储日期,例如1970-01-01payment_plan_days存储天数,30,70,任何整数。

如何将payment_plan_days添加到transaction_date以创建新列membership_expire_date

我尝试使用下面的代码并且它不起作用,因为它们不是相同的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']

2 个答案:

答案 0 :(得分:1)

我认为你需要to_timedelta

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

样品:

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

答案 1 :(得分:1)

同样的想法,jezrael仅使用datetime的timedelta函数回答:

from datetime import timedelta
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.loc[:, 'expiration_date'] = list(map(lambda td, ppd: td+timedelta(ppd), df['transaction_date'], df['payment_plan_days']))