计算Pandas中每列的唯一符号数

2024-04-27 04:37:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

提前谢谢


Tags: indffor符号tempcol2col1cc
3条回答

有一种方法:

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

col1    3
col2    4

选项1
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

也许吧

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

相关问题 更多 >