Вы можете упростить решение с помощью value_counts
:
df = pd.DataFrame({
'A':list('abcdef'),
'F':list('aaabbc')
})
print (df)
A F
0 a a
1 b a
2 c a
3 d b
4 e b
5 f c
def count_entries(df,col_name):
""" Return a dictionary with counts of occurrences as value for each key"""
return df[col_name].value_counts().to_dict()
Или используйте collections.Counter
:
from collections import Counter
def count_entries(df,col_name):
""" Return a dictionary with counts of occurrences as value for each key"""
return dict(Counter(df[col_name]))
result = count_entries(df, 'F')
print (result)
{'a': 3, 'b': 2, 'c': 1}