且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在每一列的DataFrame中查找不同元素的数量

更新时间:2022-12-09 09:35:38

pandas 0.20 开始,我们可以直接在DataFrame上使用nunique,即:

As of pandas 0.20 we can use nunique directly on DataFrames, i.e.:

df.nunique()
a    4
b    5
c    1
dtype: int64

其他旧版选项:

Other legacy options:

您可以对df进行转置,然后使用 nunique 按行:

You could do a transpose of the df and then using apply call nunique row-wise:

In [205]:
df = pd.DataFrame({'a':[0,1,1,2,3],'b':[1,2,3,4,5],'c':[1,1,1,1,1]})
df

Out[205]:
   a  b  c
0  0  1  1
1  1  2  1
2  1  3  1
3  2  4  1
4  3  5  1

In [206]:
df.T.apply(lambda x: x.nunique(), axis=1)

Out[206]:
a    4
b    5
c    1
dtype: int64

编辑

@ajcr指出,转置是不必要的:

As pointed out by @ajcr the transpose is unnecessary:

In [208]:
df.apply(pd.Series.nunique)

Out[208]:
a    4
b    5
c    1
dtype: int64