我想知道如何计算数据帧中单个列中出现的唯一符号的数量。例如:
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
提前致谢
答案 0 :(得分:5)
这是一种方式:
df.apply(lambda x: len(set(''.join(x.astype(str)))))
col1 3
col2 4
答案 1 :(得分:5)
选项1
dict comprehension中的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
答案 2 :(得分:5)
也许
df.sum().apply(set).str.len()
Out[673]:
col1 3
col2 4
dtype: int64
答案 3 :(得分:1)
还有一个选择:
In [38]: df.applymap(lambda x: len(set(x))).sum()
Out[38]:
col1 3
col2 4
dtype: int64