数据框-在列中查找常用短语
我有一个这样的 df
df a
name | list_of_skills
---------------------------
brian | ['coding in python', 'halo 3']
jon | ['coding in python', 'running', 'sports']
有什么方法可以让我得到一些最常见的短语的数量,如下所示:
'coding in python' 2
'halo 3' 1
'running' 1
'sports' 1
只是一个简单的短语计数器而不遍历每个列表并将其与所有其他列表进行比较?
回答
使用Series.explode有Series.value_counts:
s = df['list_of_skills'].explode().value_counts()
print (s)
coding in python 2
running 1
sports 1
halo 3 1
Name: list_of_skills, dtype: int64
如果需要数据帧:
df1 = s.rename_axis('words').reset_index(name='counts')
print (df1)
words counts
0 coding in python 2
1 running 1
2 sports 1
3 halo 3 1