summation of values in pandas
<p>There is a pandas dataframe with two columns 'key' and 'value'.
I want summation of values corresponding to the rows with key in range(key-3,key-1) to be put in a new column 'new_value' in the original dataframe.
for eg:</p>

<p>df:</p>

<pre><code>key  value
1     2
2     1
3     1
5     1
7     1
</code></pre>

<p>output would be:</p>

<pre><code>key value new_value
1   2     0
2   1     2
3   1     3
5   1     2
7   1     1
</code></pre>

<p>You can take a look at this :</p>

<pre><code>In [52]: df
Out[52]: 
   key  value
0    1      2
1    2      1
2    3      1
3    5      1
4    7      1

In [53]: df['new_value'] = df.apply(lambda x: df[(df['key'] &gt;= x['key'] - 3) &amp; (df['key'] &lt;= x['key'] - 1)]['value'].sum(), axis=1)

In [54]: df
Out[54]: 
   key  value  new_value
0    1      2          0
1    2      1          2
2    3      1          3
3    5      1          2
4    7      1          1
</code></pre>

<p>I'm using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> to compute the new value for each row.</p>

python pandas