Pandas 每列数据框中的唯一数

Pandas number of uniques in each column dataframe

对于无需遍历列的数据帧,是否有等效于 nunique() in Series 的方法?基本上确定每个数据框列中的唯一数,例如

  >>> df
   a  b
0  x  x
1  x  y
2  x  z
3  x  4

会给出:

array([1, 4])

IIUC 你可以使用 apply:

print (df.apply(lambda x: x.nunique()))
a    1
b    4
dtype: int64

print (df.apply(pd.Series.nunique))
a    1
b    4
dtype: int64

print (df.apply(lambda x: len(x.unique())))
a    1
b    4
dtype: int64

print (df.apply(lambda x: x.nunique()).values)
[1 4]