title: How can I do a rolling window aggregate within groupby in Pandas?
body: <p><strong>EDIT</strong>: I realized by time window was not what I had in mind, so the below solution actually seems to work :/</p>
  
  <hr>
  
  <p>I would like to do a rolling window aggregation over a variable <code>val</code> and a time <code>t</code>, but each window should be within a categorical variable <code>cat</code>.</p>
  
  <p>I also want to keep the old columns and just generate a new aggregated column next to them.</p>
  
  <p>So I tried</p>
  
  <pre><code>import random
  import numpy as np
  import pandas as pd
  
  N=100
  np.random.seed(0)
  random.seed(0)
  
  df = pd.DataFrame({"t": [pd.Timestamp(1514764800+random.randint(0, 10000000), unit="s") for _ in range(N)],
                     "cat": np.random.choice(["a", "b", "c"], size=N),
                     "val": np.random.randint(1,10, size=N),
                    })
  
  df_agg = (df.groupby("cat", group_keys=False)
              .apply(lambda d:d.assign(aggval=d.sort_values("t")
                                               .rolling("7d", on="t")
                                               ["val"].agg("sum")
                                       )
                     )
            ).sort_values(["cat", "t"])
  
  --&gt;
     cat                   t  val  aggval
  41   a 2018-01-01 05:19:33    5     5.0
  38   a 2018-01-03 17:26:20    9    14.0
  2    a 2018-01-08 20:40:15    6    15.0
  36   a 2018-01-13 02:14:38    9    15.0
  22   a 2018-01-15 07:39:52    1    16.0
  89   a 2018-01-16 13:59:03    6    16.0
  85   a 2018-01-18 10:36:42    9    25.0
  ...
  </code></pre>
  
  <p>but that does not seem to get the order right.</p>
  
  <p>What is the correct way to do that?</p>