【问题标题】:Count unique symbols per column in Pandas计算 Pandas 中每列的唯一符号
【发布时间】:2018-03-26 20:19:17
【问题描述】:

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

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

提前致谢

【问题讨论】:

  • 所以要清楚,如果 col3 是 {col3: eee, rrr, ere} 它会返回 2?
  • 没错:)

标签: python pandas dataframe set unique


【解决方案1】:

选项 1
dict 理解中的str.join + set
对于这样的问题,我宁愿回退到 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

【讨论】:

  • agg 通常不需要通过groupby('') 调用或类似的方式进行吗?
  • @akozi 根据 0.20,agg 是一阶函数。
【解决方案2】:

这是一种方法:

df.apply(lambda x: len(set(''.join(x.astype(str)))))

col1    3
col2    4

【讨论】:

    【解决方案3】:

    也许

    df.sum().apply(set).str.len()
    Out[673]: 
    col1    3
    col2    4
    dtype: int64
    

    【讨论】:

      【解决方案4】:

      另一种选择:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-30
        • 2014-04-07
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多