+-
python – 查找每列DataFrame中不同元素的数量
我试图使用Pandas在每列中找到不同值的计数.这就是我做的.

import pandas as pd
import numpy as np

# Generate data.
NROW = 10000
NCOL = 100
df = pd.DataFrame(np.random.randint(1, 100000, (NROW, NCOL)),
                  columns=['col' + x for x in np.arange(NCOL).astype(str)])

我需要计算每列的不同元素的数量,如下所示:

col0    9538
col1    9505
col2    9524

最有效的方法是什么,因为此方法将应用于大小超过1.5GB的文件?

根据答案,df.apply(lambda x:len(x.unique()))是最快的(notebook).

%timeit df.apply(lambda x:len(x.unique()))
10个循环,最佳3:每循环49.5毫秒
%timeit df.nunique()
10个循环,最佳3:59.7 ms每个循环
%timeit df.apply(pd.Series.nunique)
10个循环,最佳3:每循环60.3毫秒
%timeit df.T.apply(lambda x:x.nunique(),axis = 1)
10个循环,最佳3:60.5 ms每循环

最佳答案
从pandas 0.20开始,我们可以直接在DataFrames上使用nunique,即:

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

其他遗留选项:

您可以对df进行转置,然后使用apply逐行调用nunique

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指出的那样,转置是不必要的:

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

Out[208]:
a    4
b    5
c    1
dtype: int64
点击查看更多相关文章

转载注明原文:python – 查找每列DataFrame中不同元素的数量 - 乐贴网