代码之家  ›  专栏  ›  技术社区  ›  Alien13

计算熊猫中每列的唯一符号

  •  4
  • Alien13  · 技术社区  · 8 年前

    我想知道如何计算数据帧中单个列中出现的唯一符号的数量。例如:

    df = pd.DataFrame({'col1': ['a', 'bbb', 'cc', ''], 'col2': ['ddd', 'eeeee', 'ff', 'ggggggg']})
    
    df  col1    col2
    0      a    ddd
    1    bbb    eeeee
    2     cc    ff
    3           gggggg
    

    它应该计算col1包含3个唯一符号,col2包含4个唯一符号。

    到目前为止,我的代码(但这可能是错误的):

    unique_symbols = [0]*203
    i = 0
    for col in df.columns:
        observed_symbols = []
        df_temp = df[[col]]
        df_temp = df_temp.astype('str')
    
        #This part is where I am not so sure
        for index, row in df_temp.iterrows():
            pass
    
        if symbol not in observed_symbols:
            observed_symbols.append(symbol)
        unique_symbols[i] = len(observed_symbols)
        i += 1
    

    提前感谢

    4 回复  |  直到 7 年前
        1
  •  5
  •   cs95 abhishek58g    8 年前

    选项1
    str.join + set 内部a 听写理解
    对于这样的问题,我更倾向于使用python,因为它速度更快。

    {c : len(set(''.join(df[c]))) for c in df.columns}
    

    {'col1': 3, 'col2': 4}
    

    选项2
    agg
    如果你想呆在熊猫的空间里。

    df.agg(lambda x: set(''.join(x)), axis=0).str.len()
    

    或

    df.agg(lambda x: len(set(''.join(x))), axis=0)
    

    col1    3
    col2    4
    dtype: int64
    
        2
  •  5
  •   sacuL    8 年前

    这里有一种方法:

    df.apply(lambda x: len(set(''.join(x.astype(str)))))
    
    col1    3
    col2    4
    
        3
  •  5
  •   BENY    8 年前

    大概

    df.sum().apply(set).str.len()
    Out[673]: 
    col1    3
    col2    4
    dtype: int64
    
        4
  •  1
  •   MaxU - stand with Ukraine    8 年前

    还有一个选项:

    In [38]: df.applymap(lambda x: len(set(x))).sum()
    Out[38]:
    col1    3
    col2    4
    dtype: int64