How to get date after subtracting days in pandas
<p>I have a dataframe:</p>

<pre><code>In [15]: df
Out[15]: 
        date  day
0 2015-10-10   23
1 2015-12-19    9
2 2016-03-05   34
3 2016-09-17   23
4 2016-04-30    2
</code></pre>

<p>I want to subtract the number of days from the date and create a new column.</p>

<pre><code>In [16]: df.dtypes
Out[16]: 
date    datetime64[ns]
day              int64
</code></pre>

<p>Desired output something like:</p>

<pre><code>In [15]: df
Out[15]: 
        date  day date1
0 2015-10-10   23 2015-09-17
1 2015-12-19    9 2015-12-10
2 2016-03-05   34 2016-01-29
3 2016-09-17   23 2016-08-25
4 2016-04-30    2 2016-04-28
</code></pre>

<p>I tried but this does not work:</p>

<pre><code>df['date1']=df['date']+pd.Timedelta(df['date'].dt.day-df['day'])
</code></pre>

<p>it throws error :</p>

<blockquote>
  <p>TypeError: unsupported type for timedelta days component: Series</p>
</blockquote>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a>:</p>

<pre><code>df['date1'] = df['date'] -  pd.to_timedelta(df['day'], unit='d')

print (df)
        date  day      date1
0 2015-10-10   23 2015-09-17
1 2015-12-19    9 2015-12-10
2 2016-03-05   34 2016-01-31
3 2016-09-17   23 2016-08-25
4 2016-04-30    2 2016-04-28
</code></pre>

<p>If need <code>Timedelta</code> use <code>apply</code>, but it is slowier:</p>

<pre><code>df['date1'] = df['date'] -  df.day.apply(lambda x: pd.Timedelta(x, unit='D'))

print (df)
        date  day      date1
0 2015-10-10   23 2015-09-17
1 2015-12-19    9 2015-12-10
2 2016-03-05   34 2016-01-31
3 2016-09-17   23 2016-08-25
4 2016-04-30    2 2016-04-28
</code></pre>

<p><strong>Timings</strong>:</p>

<pre><code>#[5000 rows x 2 columns]
df = pd.concat([df]*1000).reset_index(drop=True)

In [252]: %timeit df['date'] -  df.day.apply(lambda x: pd.Timedelta(x, unit='D'))
10 loops, best of 3: 45.3 ms per loop

In [253]: %timeit df['date'] -  pd.to_timedelta(df['day'], unit='d')
1000 loops, best of 3: 1.71 ms per loop
</code></pre>

python pandas