【问题标题】:Add 'document_id' column to pandas dataframe of word-id's and wordcounts将 'document id' 列添加到 word-is 和字数的 pandas 数据框
【发布时间】:2018-10-04 03:29:36
【问题描述】:

我有以下数据集:

import pandas as pd
jsonDF = pd.DataFrame({'DOCUMENT_ID':[263403828328665088,264142543883739136], 'MESSAGE':['@Zuora wants to help @Network4Good with Hurric...','@ztrip please help spread the good word on hel...']})

DOCUMENT_ID             MESSAGE
0   263403828328665088  @Zuora wants to help @Network4Good with Hurric...
1   264142543883739136  @ztrip please help spread the good word on hel...

我正在尝试以

的形式重塑我的数据
docID   wordID  count
0   1   118     1
1   1   285     1
2   1   1229    1
3   1   1688    1
4   1   2068    1

我用了以下

r=[]
for i in jsonDF['MESSAGE']:
    for j in sortedValues(wordsplit(i)):
        r.append(j)
IDCount_Re=pd.DataFrame(r)
IDCount_Re[:5]

给我以下结果

0               17
1   help         2
2   wants        1
3   hurricane   1
4   relief      1
5   text        1
6   sandy       1
7   donate      1
8              6
9   please    1

我可以统计字数

我不知道将 Document_ID 附加到上述数据框中。

以下函数用于拆分单词

from nltk.corpus import stopwords 
import re

def wordsplit(wordlist):
    j=wordlist
    j=re.sub(r'\d+', '', j)
    j=re.sub('RT', '',j)
    j=re.sub('http', '', j)
    j = re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", j)
    j=j.lower()
    j=j.strip()
    if not j in stopwords.words('english'):
        yield j

def wordSplitCount(wordlist):
    '''merges a list into string, splits it, removes stop words and 
    then counts the occurrences returning an ordered dictitonary'''
    #stopwords=set(stopwords.words('english'))
    string1=''.join(list(itertools.chain(filter(None, wordlist))))
    cnt=Counter()
    j = []
    for i in string1.split(" "):
        i=re.sub(r'&', ' ', i.lower())
        if i not in stopwords.words('english'):
            cnt[i]+=1
    return OrderedDict(cnt)

def sortedValues(wordlist):
    '''creates a dictionary list of occurenced w/ values descending'''
    d=wordSplitCount(wordlist)
    return sorted(d.items(), key=lambda t: t[1], reverse=True)

更新:此处的解决方案:

string split and and assign unique ids to Pandas DataFrame

【问题讨论】:

  • 你可以将你的 i,j 循环和低效的追加组合到一个生成器表达式中:wordcounts = Counter(word) for word in sortedValues(wordsplit(msg)) for msg in jsonDF['MESSAGE'])
  • 但这并不附加 DOCUMENT_ID,是吗?
  • 我没这么说。我建议稍微清理一下您的代码。还有像合并你的正则表达式re.sub(r'(\d+|RT|http)', '', j)
  • 您的sortedValues() 应替换为Counter().most_common()

标签: pandas nltk word-count


【解决方案1】:

“DOCUMENT_ID”是jsonDF 每一行中的两个字段之一。您当前的代码无法访问它,因为它直接在 jsonDF['MESSAGE'] 上运行。

这是一些无效的伪代码 - 类似于:

for _, row in jsonDF.iterrows():
    doc_id, msg = row
    words = [word for word in wordsplit(msg)][0].split() # hack
    wordcounts = Counter(words).most_common() # sort by decr frequency

然后做一个pd.concat(pd.DataFrame({'DOCUMENT_ID': doc_id, ... 并从wordcounts 获取“wordId”和“count”字段。

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 1970-01-01
    • 2015-08-11
    • 2017-04-22
    • 2017-05-02
    • 2021-03-18
    • 2016-03-28
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多