How to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column
<p><br>A very simple example just for understanding.</p>

<p><strong>The goal is to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column.</strong></p>

<p>I have the following DataFrame:</p>

<pre><code>import numpy as np
import pandas as pd

s = pd.Series([1,2,3,2,1,2,3,2,1])    
df = pd.DataFrame({'DATA':s, 'POINTS':0})

df
</code></pre>

<p><a href="http://i.stack.imgur.com/8dZmD.png" rel="nofollow"><img src="http://i.stack.imgur.com/8dZmD.png" alt="DataFrame start"></a></p>

<p><em>Note: I don't even know how to format the Jupyter Notebook results in the Stackoverflow edit window, so I copy and paste the image, I beg your pardon.</em></p>

<p>The <strong>DATA</strong> column shows the observed data; the <strong>POINTS</strong> column, initialized to 0, is used to collect the output of a "rolling" function applied to DATA column, as explained in the following.</p>

<p>Set a window = 4</p>

<pre><code>nwin = 4
</code></pre>

<p>Just for the example, <strong>the "rolling" function calculate the max</strong>.</p>

<p>Now let me use a drawing to explain what I need.</p>

<p><a href="http://i.stack.imgur.com/GflSG.png" rel="nofollow"><img src="http://i.stack.imgur.com/GflSG.png" alt="Algo flow"></a></p>

<p>For every iteration, the rolling function calculate the maximum of the data in the window; then the POINT at the same index of the max DATA is incremented by 1.</p>

<p>The final result is:</p>

<p><a href="http://i.stack.imgur.com/7P1Z5.png" rel="nofollow"><img src="http://i.stack.imgur.com/7P1Z5.png" alt="DataFrame end"></a></p>

<p>Can you help me with the python code?</p>

<p>I really appreciate your help.<br>
Thank you in advance for your time,<br>
Gilberto</p>

<p><em>P.S. Can you also suggest how to copy and paste Jupyter Notebook formatted cell to Stackoverflow edit window? Thank you.</em></p>

<p>IIUC the explanation by @IanS (thanks again!), you can do</p>

<pre><code>In [75]: np.array([df.DATA.rolling(4).max().shift(-i) == df.DATA for i in range(4)]).T.sum(axis=1)
Out[75]: array([0, 0, 3, 0, 0, 0, 3, 0, 0])
</code></pre>

<p>To update the column:</p>

<pre><code>In [78]: df = pd.DataFrame({'DATA':s, 'POINTS':0})

In [79]: df.POINTS += np.array([df.DATA.rolling(4).max().shift(-i) == df.DATA for i in range(4)]).T.sum(axis=1)

In [80]: df
Out[80]: 
   DATA  POINTS
0     1       0
1     2       0
2     3       3
3     2       0
4     1       0
5     2       0
6     3       3
7     2       0
8     1       0
</code></pre>

python pandas dataframe calculated-columns