【问题标题】:Finding count of distinct elements in DataFrame in each column在每列中查找 DataFrame 中不同元素的计数
【发布时间】:2015-08-10 18:29:05
【问题描述】:

我正在尝试使用 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 loops, best of 3: 49.5 ms per loop %timeit df.nunique() 10 loops, best of 3: 59.7 ms per loop %timeit df.apply(pd.Series.nunique) 10 loops, best of 3: 60.3 ms per loop %timeit df.T.apply(lambda x: x.nunique(), axis=1) 10 loops, best of 3: 60.5 ms per loop

【问题讨论】:

    标签: python numpy pandas


    【解决方案1】:

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

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

    其他传统选项:

    您可以对 df 进行转置,然后使用 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 所指出的,转置是不必要的:

    In [208]:
    df.apply(pd.Series.nunique)
    
    Out[208]:
    a    4
    b    5
    c    1
    dtype: int64
    

    【讨论】:

    • 谢谢!我只是想澄清一下,所以发生的情况是,对于 df 中的每一列,每次都传递给 apply 一个,它使用 pd.Series.nunique 来获取唯一计数?所以基本上对于每一列它运行 .nunique() 函数?
    【解决方案2】:

    Pandas.Series 有一个 .value_counts() 函数,可以提供您想要的功能。 Check out the documentation for the function.

    【讨论】:

    • 你能演示一下你没有发布代码和输出时的样子吗
    • @EdChum - df.value_counts(dropna = False).sort_index() 会起作用。
    • >AttributeError: 'DataFrame' 对象没有属性 'value_counts'
    • 仅适用于系列,因此您应该将数据框子集为一列。
    【解决方案3】:

    最近,我在计算 DataFrame 中每一列的唯一值时遇到了同样的问题,我发现其他一些函数比 apply 函数运行得更快:

    #Select the way how you want to store the output, could be pd.DataFrame or Dict, I will use Dict to demonstrate:
    col_uni_val={}
    for i in df.columns:
        col_uni_val[i] = len(df[i].unique())
    
    #Import pprint to display dic nicely:
    import pprint
    pprint.pprint(col_uni_val)
    

    这对我来说几乎比df.apply(lambda x: len(x.unique()))快两倍

    【讨论】:

      【解决方案4】:

      这里已经有一些很好的答案 :) 但是这个似乎不见了:

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

      从 pandas 0.20.0 开始,DataFrame.nunique() 也可用。

      【讨论】:

        【解决方案5】:
        df.apply(lambda x: len(x.unique()))
        

        【讨论】:

          【解决方案6】:

          只需要对 pandas_python 中所有列的唯一值超过 20 个的列进行隔离:

          enter code here
          col_with_morethan_20_unique_values_cat=[]
          for col in data.columns:
              if data[col].dtype =='O':
                  if len(data[col].unique()) >20:
          
                  ....col_with_morethan_20_unique_values_cat.append(data[col].name)
                  else:
                      continue
          
          print(col_with_morethan_20_unique_values_cat)
          print('total number of columns with more than 20 number of unique value is',len(col_with_morethan_20_unique_values_cat))
          
          
          
           # The o/p will be as:
          ['CONTRACT NO', 'X2','X3',,,,,,,..]
          total number of columns with more than 20 number of unique value is 25
          

          【讨论】:

            【解决方案7】:

            为@CaMaDuPe85给出的答案添加示例代码

            df = pd.DataFrame({'a':[0,1,1,2,3],'b':[1,2,3,4,5],'c':[1,1,1,1,1]})
            df
            
            # df
                a   b   c
            0   0   1   1
            1   1   2   1
            2   1   3   1
            3   2   4   1
            4   3   5   1
            
            
            for cs in df.columns:
                print(cs,df[cs].value_counts().count()) 
                # using value_counts in each column and count it 
            
            # Output
            
            a 4
            b 5
            c 1
            

            【讨论】:

              【解决方案8】:

              我找到了:

              df.agg(['nunique']).T
              

              更快

              【讨论】:

                猜你喜欢
                • 2015-10-31
                • 2021-12-09
                • 2012-04-11
                • 2023-02-08
                • 2018-12-09
                • 2015-03-07
                • 2013-03-10
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多