从 Pandas 数据框中计算不同的单词 [英] Count distinct words from a Pandas Data Frame
本文介绍了从 Pandas 数据框中计算不同的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Pandas 数据框,其中一列包含文本.我想获得整个列中出现的唯一单词列表(空格是唯一的分隔符).
I've a Pandas data frame, where one column contains text. I'd like to get a list of unique words appearing across the entire column (space being the only split).
import pandas as pd
r1=['My nickname is ft.jgt','Someone is going to my place']
df=pd.DataFrame(r1,columns=['text'])
输出应如下所示:
['my','nickname','is','ft.jgt','someone','going','to','place']
计数也无妨,但这不是必需的.
It wouldn't hurt to get a count as well, but it is not required.
推荐答案
使用 set
来创建唯一元素的序列.
Use a set
to create the sequence of unique elements.
对 df
进行一些清理以获取小写字符串并拆分:
Do some clean-up on df
to get the strings in lower case and split:
df['text'].str.lower().str.split()
Out[43]:
0 [my, nickname, is, ft.jgt]
1 [someone, is, going, to, my, place]
此列中的每个列表都可以传递给 set.update
函数以获得唯一值.使用 apply
这样做:
Each list in this column can be passed to set.update
function to get unique values. Use apply
to do so:
results = set()
df['text'].str.lower().str.split().apply(results.update)
print(results)
set(['someone', 'ft.jgt', 'my', 'is', 'to', 'going', 'place', 'nickname'])
或与评论中的 Counter()
一起使用:
Or use with Counter()
from comments:
from collections import Counter
results = Counter()
df['text'].str.lower().str.split().apply(results.update)
print(results)
这篇关于从 Pandas 数据框中计算不同的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文