在所有列中查找唯一值
问题描述:
我可以检查给定列的唯一值的数量。在所有列中查找唯一值
len(df.createdby.unique())
但是有没有一种方法知道唯一值acorss所有列? 我可以运行这2个循环,并得到我需要的结果。但我正在寻找一种达到此目标的pythonic和优雅的方式。
for i in df.columns:
exec("print len(df.%s.unique())" % i)
for i in df.columns:
print i
答
我想你需要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
答
使用drop_duplicates
方法
len(df.drop_duplicates())
答
从0.20.0
起使用df.nunique()
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
这不返回每列中唯一值的数量。 – shantanuo