我正在尝试计算数据框“文本”列中主题标签词的频率。
index text
1 ello ello ello ello #hello #ello
2 red green blue black #colours
3 Season greetings #hello #goodbye
4 morning #goodMorning #hello
5 my favourite animal #dog
word_freq = df.text.str.split(expand=True).stack().value_counts()
上面的代码将对文本列中的所有字符串执行频率计数,但我只是返回主题标签频率。
例如,在上面的数据帧上运行代码后,它应该返回
#hello 3
#goodbye 1
#goodMorning 1
#ello 1
#colours 1
#dog 1
有没有一种方法可以稍微重新调整我的 word_freq 代码,以便它只计算主题标签单词并以我上面放置的方式返回它们?提前致谢。
Use Series.str.findall https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.findall.html在列上text
找到所有主题标签词然后使用Series.explode https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html + Series.value_counts https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html:
counts = df['text'].str.findall(r'(#\w+)').explode().value_counts()
另一个想法使用Series.str.split https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html + DataFrame.stack https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html:
s = df['text'].str.split(expand=True).stack()
counts = s[lambda x: x.str.startswith('#')].value_counts()
Result:
print(counts)
#hello 3
#dog 1
#colours 1
#ello 1
#goodMorning 1
#goodbye 1
Name: text, dtype: int64
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)