Python Pandas .Apply Function to Vectorized Form
<p>I'm trying to convert the following .apply transformation to a vectorized form which will run faster.  I've tried .where, and I've tried normal boolean indexing, however my solutions are not working.  Please send me in the right direction</p>

<pre><code>oneDayDelta = datetime.timedelta(days=1)
def correct_gps_datetimestamp(row):
    new_dts = row['GPS_DateTime']
    if row['Created'].hour == 0 and  row['GPS_DateTime'].hour &gt; 10:
        new_dts = row['GPS_DateTime'] - oneDayDelta
    return(new_dts)

allData['GPS_DateTime'] = allData.apply(correct_gps_datetimestamp,axis=1)
</code></pre>

<p>Non working solution:</p>

<pre><code>allData['GPS_DateTime'] = allData.where(allData['Created'].hour == 0 &amp; allData['GPS_DateTime'].hour &gt; 10,allData['GPS_DateTime'] - datetime.timedelta(days=1))
</code></pre>

<p>You can do this in a single line using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a>:</p>

<pre><code>allData['GPS_DateTime'] = np.where((allData['Created'].dt.hour == 0) &amp;  (allData['GPS_DateTime'].dt.hour &gt; 10), allData['GPS_DateTime'] - oneDayDelta, allData['GPS_DateTime'])
</code></pre>

<p>Note that the datetimes have <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html" rel="nofollow"><code>dt.hour</code></a> accessor to get the hours as int value, this allows you to compare the entire df, note that we use <code>&amp;</code> here instead of <code>and</code> as we're comparing arrays. Additionally we have to use parentheses around the conditions due to operator precedence.</p>

<pre><code>(allData['Created'].dt.hour == 0) &amp;  (allData['GPS_DateTime'].dt.hour &gt; 10)
</code></pre>

<p>So where this condition is met it returns your datetime column minus the one data timedelta, otherwise it just returns your column</p>

python pandas