For your pleasure, this is not a very simple read-out loud solution that does not use reset_indexeither apply, or agg, or, or anonymous functions. However, it uses zipand Counterfrom the standard library.
import pandas as pd
from collections import Counter
ex = pd.DataFrame([[1, 2, 3], [6, 7, 8], [1, 7, 9]],
columns=["A", "B", "C"]).set_index(["A", "B"])
A_val, nunique_B = zip(*[(k, len(Counter(v.index.labels[v.index.names.index('B')])))
for k, v in ex.groupby(level='A')])
pd.Series(nunique_B, index=pd.Int64Index(A_val, name='A'))
returns
A
1 2
6 1
dtype: int32
In addition, for the sake of generality, I do not assume that it Bis at level 1 of the index.
source
share