Rolling sum in subgroups of a dataframe (pandas)
<p>I have <code>sessions</code> dataframe that contains <code>E-mail</code> and <code>Sessions</code> (int) columns. </p>

<p>I need to calculate rolling sum of sessions <em>per email</em> (i.e. not globally).</p>

<p>Now, the following works, but it's painfully slow:</p>

<pre><code>emails = set(list(sessions['E-mail']))
ses_sums = []
for em in emails:
    email_sessions = sessions[sessions['E-mail'] == em]
    email_sessions.is_copy = False
    email_sessions['Session_Rolling_Sum'] = pd.rolling_sum(email_sessions['Sessions'], window=self.window).fillna(0)
    ses_sums.append(email_sessions)
df = pd.concat(ses_sums, ignore_index=True)
</code></pre>

<p>Is there a way of achieving the same in <code>pandas</code>, but using <code>pandas</code> operators on a dataframe instead of creating separate dataframes for each email and then concatenating them?</p>

<p>(either that or some other way of making this faster)</p>

<pre><code>np.random.seed([3,1415])
df = pd.DataFrame({'E-Mail': np.random.choice(list('AB'), 20),
                   'Session': np.random.randint(1, 10, 20)})

df.groupby('E-Mail').Session.rolling(3).sum()

E-Mail    
A       0      NaN
        2      NaN
        4     11.0
        5      7.0
        7     10.0
        12    16.0
        15    16.0
        17    16.0
        18    17.0
        19    18.0
B       1      NaN
        3      NaN
        6     18.0
        8     14.0
        9     16.0
        10    12.0
        11    13.0
        13    16.0
        14    20.0
        16    22.0
Name: Session, dtype: float64
</code></pre>

python performance pandas