Reputation: 1303
I've tried datetime.timedelta on the series, as well as pd.DateOffset. Neither works. I do know I could iterate over this dataframe and add them manually, but I was looking for a vectorized approach.
Example:
d = {pd.Timestamp('2015-01-02'):{'days_delinquent':11}, pd.Timestamp('2015-01-15'):{'days_delinquent':23}}
>>> dataf = pd.DataFrame.from_dict(d,orient='index')
>>> dataf
days_delinquent
2015-01-02 11
2015-01-15 23
Just trying to add 11 and 23 days to the rows below. The column I'm adding to in real life is not the index, but I can obviously just make it the index when doing this.
I guess this wasn't self explanatory, but the output would the be a new column with Date(Index in this case) + datetime.timedelta(days=dataf['days_delinquent'])
Upvotes: 1
Views: 75
Reputation: 142166
You can convert your days_delinquent
column to timedelta64[D]
(offset in days) and add it to the index, eg:
import pandas as pd
d = {pd.Timestamp('2015-01-02'):{'days_delinquent':11}, pd.Timestamp('2015-01-15'):{'days_delinquent':23}}
df = pd.DataFrame.from_dict(d,orient='index')
df['returned_on'] = df.index + df.days_delinquent.astype('timedelta64[D]')
Much nicer (thanks DSM) is to use pd.to_timedelta
so the units are more easily changed if needs be:
df['returned_on'] = df.index + pd.to_timedelta(df.days_delinquent, 'D')
Gives you:
days_delinquent returned_on
2015-01-02 11 2015-01-13
2015-01-15 23 2015-02-07
Upvotes: 3
Reputation: 109546
dataf['result'] = [d + datetime.timedelta(delta)
for d, delta in zip(dataf.index, dataf.days_delinquent)]
dataf
Out[56]:
days_delinquent result
2015-01-02 11 2015-01-13
2015-01-15 23 2015-02-07
Upvotes: 1
Reputation: 7822
import pandas as pd
d = {pd.Timestamp('2015-01-02'):{'days_delinquent':11},
pd.Timestamp('2015-01-15'):{'days_delinquent':23}}
df = pd.DataFrame.from_dict(d,orient='index')
def add_days(x):
return x['index'] + pd.Timedelta(days=x['days_delinquent'])
df.reset_index().apply(add_days,axis=1)
Output:
0 2015-01-13
1 2015-02-07
dtype: datetime64[ns]
Upvotes: 1