title: Pandas groupby with dynamic group membership
body: <p>I want to group my dataframe df on the column axis, according to the group membership defined by dfGroups:</p>
  <pre><code>df
  Out[87]: 
     A  B
  0  1  2
  1  3  4
  2  5  6
  </code></pre>
  <p>Importantly, the group membership of a column changes from row to row:</p>
  <pre><code>dfGroups
  Out[106]: 
          A       B
  0  group1  group2
  1  group1  group3
  2  group2  group3
  </code></pre>
  <p>I can accomplish this via the following:</p>
  <pre><code>df.stack().groupby([pd.Grouper(level=0), dfGroups.stack()]).mean().unstack()
  Out[107]: 
     group1  group2  group3
  0     1.0     2.0     NaN
  1     3.0     NaN     4.0
  2     NaN     5.0     6.0
  </code></pre>
  <p>But it feels clunky and I'm wondering if there's a more idiomatic way of accomplishing it.</p>