title: How can I demean variables by group in patsy?
body: <p>for a regression I want to subtract group specific means from the (many) right side variables (they are interactions).</p>
  
  <p>Without group specificity this is easy of course.</p>
  
  <pre><code>y, X = dmatrices('lhs ~ center(x1 * k1)', df)
  </code></pre>
  
  <p>How could I do this with group specific means? The Problem is that the right hand side contains many interaction terms which I cannot naively create upfront.</p>
  
  <p>So I would like to do something like this upfront:</p>
  
  <pre><code>df['x1_times_k1'] = df['x1'] * df['k1']
  df['x1_times_k1_centered'] = df.groupby('group')['x1_times_k1'].transform('mean')
  
  y, X = dmatrices('lhs ~ x1_times_k1_centered', df)
  </code></pre>
  
  <p>But it won't be feasible, any suggestions?</p>
  
  <p><strong>EDIT</strong> 
  Alternatively: is there a way to standardize the data by group in scikit? </p>
  
  <p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler</a></p>