我有一个包含一列列表的数据框,内容如下:
df
pos_tag
0 ['Noun','verb','adjective']
1 ['Noun','verb']
2 ['verb','adjective']
3 ['Noun','adverb']
...
我想得到的是每个唯一元素作为字典出现在整个列中的时间:
desired output:
my_dict = {'Noun':3, 'verb':3, 'adjective':2, 'adverb':1}
答案 0 :(得分:2)
使用Series.explode
以及Series.value_counts
和Series.to_dict
:
freq = df['pos_tag'].explode().value_counts().to_dict()
结果:
# print(freq)
{'Noun':3, 'verb':3, 'adjective':2, 'adverb':1}
答案 1 :(得分:1)
要提高性能,请使用Counter
,将嵌套列表的值展平:
from collections import Counter
my_dict = dict(Counter([y for x in df['pos_tag'] for y in x]))
print (my_dict)
{'Noun': 3, 'verb': 3, 'adjective': 2, 'adverb': 1}