Count unique characters in a column in Pandas

I was wondering how to calculate the number of unique characters that occur in a single column in a data frame. For instance:

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

He must calculate that col1 contains 3 unique characters, and col2 contains 4 unique characters.

My code so far (but this may be wrong):

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

Thanks in advance

+4
source share
4 answers

Option 1
str.join + setinside understanding dict For such problems, I would prefer to return to python because it is much faster.

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

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

Option 2
agg
If you want to stay in pandas space.

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

Or

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

col1    3
col2    4
dtype: int64
+5
source

Here is one way:

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

col1    3
col2    4
+5
source

Can

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

Another option:

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

Source: https://habr.com/ru/post/1695368/


All Articles