title: Cumulative count of unique values in pandas
body: <p>I would like to cumulatively count unique values from a column in a pandas frame by week. For example, imagine that I have data like this:</p>
  
  <pre class="lang-python prettyprint-override"><code>df = pd.DataFrame({'user_id':[1,1,1,2,2,2],'week':[1,1,2,1,2,2],'module_id':['A','B','A','A','B','C']})
  </code></pre>
  
  <pre class="lang-none prettyprint-override"><code>+---+---------+------+-----------+
  |   | user_id | week | module_id |
  +---+---------+------+-----------+
  | 0 |       1 |    1 |         A |
  | 1 |       1 |    1 |         B |
  | 2 |       1 |    2 |         A |
  | 3 |       2 |    1 |         A |
  | 4 |       2 |    2 |         B |
  | 5 |       2 |    2 |         C |
  +---+---------+------+-----------+
  </code></pre>
  
  <p>What I want is a running count of the number of unique module_ids up to each week, i.e. something like this:</p>
  
  <pre class="lang-none prettyprint-override"><code>+---+---------+------+-------------------------+
  |   | user_id | week | cumulative_module_count |
  +---+---------+------+-------------------------+
  | 0 |       1 |    1 |                       2 |
  | 1 |       1 |    2 |                       2 |
  | 2 |       2 |    1 |                       1 |
  | 3 |       2 |    2 |                       3 |
  +---+---------+------+-------------------------+
  </code></pre>
  
  <p>It is straightforward to do this as a loop, for example this works:</p>
  
  <pre><code>running_tally = {}
  result = {}
  for index, row in df.iterrows():
      if row['user_id'] not in running_tally:
          running_tally[row['user_id']] = set()
          result[row['user_id']] = {}
      running_tally[row['user_id']].add(row['module_id'])
      result[row['user_id']][row['week']] = len(running_tally[row['user_id']])
  print(result)
  </code></pre>
  
  <pre class="lang-none prettyprint-override"><code>{1: {1: 2, 2: 2}, 2: {1: 1, 2: 3}}
  </code></pre>
  
  <p>But my real data frame is enormous and so I would like a vectorised algorithm instead of a loop.</p>
  
  <p>There's a similar sounding question <a href="https://stackoverflow.com/q/35759120/575530">here</a>, but looking at the accepted answer (<a href="https://stackoverflow.com/a/35759315/575530">here</a>) the original poster does not want uniqueness across dates cumulatively, as I do.</p>
  
  <p>How would I do this vectorised in pandas?</p>