考虑以下数据框:
A B E
0 bar one 1
1 bar three 1
2 flux six 1
3 flux three 2
4 foo five 2
5 foo one 1
6 foo two 1
7 foo two 2
我希望能够找到每个 A
值对应的其他列中独一无二的值的数量。
I thought the following would do it:
df.groupby('A').apply(lambda x: x.nunique())
but I get an error:
AttributeError: 'DataFrame' object has no attribute 'nunique'
I also tried with:
df.groupby('A').nunique()
but I also got the error:
AttributeError: 'DataFrameGroupBy' object has no attribute 'nunique'
Finally I tried with:
df.groupby('A').apply(lambda x: x.apply(lambda y: y.nunique()))
which returns:
A B E A bar 1 2 1 flux 1 2 2 foo 1 3 2
and seems to be correct. Strangely though, it also returns the column
A
in the result. Why?