Counting unique index values in Pandas groupby
<p>In Pandas, there is a very clean way to count the distinct values in a column within a group by operation. For example</p>

<pre><code>ex = pd.DataFrame([[1, 2, 3], [6, 7, 8], [1, 7, 9]], 
                  columns=["A", "B", "C"]).set_index(["A", "B"])
ex.groupby(level="A").C.nunique()
</code></pre>

<p>will return</p>

<pre><code>A
1    2
6    1
Name: C, dtype: int64
</code></pre>

<p>I would also like to count the distinct values in index level <code>B</code> while grouping by <code>A</code>. I can't find a clean way to access the levels of <code>B</code> from the <code>groupby</code> object. The best I've been able to come up with is:</p>

<pre><code>ex.reset_index("B", drop=False).groupby(level="A").B.nunique()
</code></pre>

<p>which correctly returns:</p>

<pre><code>A
1    2
6    1
Name: B, dtype: int64 
</code></pre>

<p>Is there a way for me to do this on the groupby without resetting the index or using an <code>apply</code> function?</p>