Python/Pandas 聚合结合NLTK

Python/Pandas aggregation combined with NLTK

我想对包含 Twitter 消息的数据集进行一些文本处理。到目前为止,我能够将数据 (.CSV) 加载到 Pandas 数据框中,并通过(自定义)列 'timestamp'.

对其进行索引
df = pandas.read_csv(f)
df.index = pandas.to_datetime(df.pop('timestamp'))

看起来有点像这样:

                                user_name user_handle
时间戳
2015-02-02 23:58:42 荷兰初创公司 NLTechStartups
2015-02-02 23:58:42 分享 NL share_NL
2015-02-02 23:58:42 BreakngAmsterdamNews iAmsterdamNews

[49570 行 x 8 列]

我可以创建一个仅包含文本的新对象(系列),如下所示:

texts = pandas.Series(df['text'])

创建这个的:

2015-06-02 14:50:54 业务更新...
2015-06-02 14:50:53 RT @ProvincieNH:Province makes Markermeerdij...
2015-06-02 14:50:53 阿姆斯特丹 - 新测速相机 Wibautstraat:在......
2015-06-02 14:50:53 阿姆斯特丹 - 新测速相机 Wibautstraat http...
2015-06-02 14:50:53 Lugar secreto em Amsterdam:Begijnhof // Hidde...
名称:文字,长度:49570

1.这个新对象是否与我的初始 df 变量类型相同(数据框),只是 columns/rows?

现在连同 nltk 一起,我可以 tokenize 使用这个字符串:

for w in words:
    print(nltk.word_tokenize(w))

这会迭代数组而不是 将 'text' 列映射 到多列 'words' 数组。 2。我该怎么做,而且我该如何计算每个单词的出现次数?

我知道有一种 unique() 方法可以用来创建不同的单词列表。但是话又说回来,我需要一个额外的列,它是我无法首先生成的数组的计数。 :) 3。或者下一步 'counting' 这些词的出现次数是 grouping?

编辑。 3:我好像需要“CountVectorizer”,感谢EdChum

documents = df['text'].values

vectorizer = CountVectorizer(min_df=0, stop_words=[])
X = vectorizer.fit_transform(documents)
print(X.toarray())

我的主要目标是计算每个单词的出现次数并选择 前 X 个结果。我觉得我走在正确的轨道上,但我不能把最后的步骤恰到好处..

此处基于 EdChums 评论是一种从 CountVectorizer 获取(我假设是全局的)字数的方法:

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
vect= CountVectorizer()

df= pd.DataFrame({'text':['cat on the cat','angel eyes has','blue red angel','one two blue','blue whales eat','hot tin roof','angel eyes has','have a cat']\
              ,'class': ['a','a','a','a','c','c','b','e']})

X = vect.fit_transform(df['text'].values)
y = df['class'].values

CountVectoriser 返回的稀疏矩阵转换为稠密矩阵,并将其和特征名称传递给 dataframe 构造函数。然后转置框架并沿 axis=1 求和以获得每个单词的总数:

word_counts =pd.DataFrame(X.todense(),columns = vect.get_feature_names()).T.sum(axis=1)
word_counts.sort(ascending=False)
word_counts[:3]

如果您只对单词的频率分布感兴趣,请考虑使用 NLTK 中的 Freq Dist

import nltk
import itertools
from nltk.probability import FreqDist
texts = ['cat on the cat','angel eyes has','blue red angel','one two blue','blue whales eat','hot tin roof','angel eyes has','have a cat']
texts = [nltk.word_tokenize(text) for text in texts]
# collapse into a single list
tokens = list(itertools.chain(*texts))

FD =FreqDist(tokens)