在所有列中查找唯一值

3

我可以检查给定列的唯一值数量。

len(df.createdby.unique())

但是有没有一种方法可以知道所有列中的唯一值?我可以运行这两个循环并获得所需的结果。但我正在寻找一种优雅和Pythonic的方法来实现这一目标。

for i in df.columns:
    exec("print len(df.%s.unique())" % i)

for i in df.columns:
    print i
3个回答

3
自版本0.20.0起,请使用df.nunique()。该函数用于计算DataFrame中每列唯一值的数量。
In [234]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]})

In [235]: df.nunique()
Out[235]:
A    3
B    1
dtype: int64

2

我认为你需要使用Series.nunique,但它并未针对DataFrame实现,因此需要使用apply

print (df.apply(lambda x: x.nunique()))

示例:

df = pd.DataFrame({'A':[1,1,3],
                   'B':[4,5,6],
                   'C':[7,7,7]})

print (df)
   A  B  C
0  1  4  7
1  1  5  7
2  3  6  7

print (df.apply(lambda x: x.nunique()))
A    2
B    3
C    1
dtype: int64

0
使用drop_duplicates方法。
len(df.drop_duplicates())

这不会返回每列唯一值的数量。 - shantanuo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接