簡體   English   中英

使用文本字符串創建Pandas數據框中出現的單詞矩陣

[英]Create a matrix of words occurring in a Pandas data frame with text strings

我有一個帶有一列文本數據的Pandas數據框。 我想將這個文本數據的每一行與我感興趣的單詞列表進行比較。比較應該產生一個矩陣,顯示該行數據文本中出現的單詞(0或1)。

輸入數據框:

text
That bear talks
The stone rocks
Tea is boiling
The bear drinks tea

輸入單詞列表:

[bear, talks, tea]

結果:

text                 bear  talks  tea
That bear talks      1     1      0
The stone rocks      0     0      0
Tea is boiling       0     0      1
The bear drinks tea  1     0      1

我在sklearn.feature_extraction.text.HashingVectorizer上找到了一些信息,但據我所知,它只需要整個數據框並在組件單詞中將其分解並計算。 我想要做的是在一個非常有限的名單上做。

使用sklearn,我做了以下事情:

from sklearn.feature_extraction.text import HashingVectorizer

countvec = HashingVectorizer()

countvec.fit_transform(resultNLdf2.text)

但這給了我以下內容:

<73319x1048576 sparse matrix of type '<class 'numpy.float64'>'
    with 1105683 stored elements in Compressed Sparse Row format>

這似乎有點大,除非我可以從這個稀疏矩陣中選擇我想要的單詞,但我不知道如何使用它。

如果我用錯誤的詞語來解釋這個問題,我很抱歉,不確定你是否會把它稱為矩陣。

編輯

我正在處理的真實數據相當大,1264555行包含推文。 至少我已經學會了不要過度簡化問題:-p。 這使得一些給定的解決方案(感謝您試圖幫助!!)因內存問題或者速度極慢而無法正常工作。 這也是我看sklearn的原因。

有:

from sklearn.feature_extraction.text import CountVectorizer

words = ['bear', 'talks', 'tea']

countvec = CountVectorizer(vocabulary=words)

countvec.fit_transform(resultNLdf2.text)

你可以通過給出一個簡單的列表來限制你想看的單詞。 但這讓我有一個問題,就是它的形式我不知道如上所述。

您可以使用Series.str.get_dummies

>>> print df.join(df.text.str.get_dummies(' ').loc[:, ['bear', 'talks', 'tea']])
                 text  bear  talks  tea
0      That bear talks     1      1    0
1      The stone rocks     0      0    0
2       Tea is boiling     0      0    0
3  The bear drinks tea     1      0    1

在使用我的初始問題給出的解決方案進行測試之后,我想堅持使用sklearn,因為它似乎非常快,並且似乎對我正在使用的大量數據沒有任何問題。 堅持使用'熊,會談,茶'的例子就是我現在正在使用的解決方案:

from sklearn.feature_extraction.text import CountVectorizer

df = pd.DataFrame(["That bear talks", "The stone rocks", "Tea is boiling", "The bear drinks tea"], columns=['text'])

words = ['bear', 'talks', 'tea']

countvec = CountVectorizer(vocabulary=words)

dfFinal = pd.DataFrame(countvec.fit_transform(df.text).toarray(), index=df.text, columns=countvec.get_feature_names())

當然,我仍然有興趣了解為什么這個或其他解決方案是好的或關於我應該考慮的事情。

由於您有一個有限的列表,您可以遍歷列表中的單詞並為每個單詞執行此操作:

df['bear'] = df['text'].str.contains('bear')

你可以使用python字符串計數

import pandas as pd

x= ["That bear talks","The stone rocks","Tea is boiling","The bear drinks tea"]
words = ['bear', 'talks', 'tea']

out=pd.DataFrame(index=x,columns=words)

for i in range(0,out.shape[0]):
    for word in words:
        out.ix[i,str(word)]= out.index[i].count(str(word))

print(out)

                    bear talks tea
That bear talks        1     1   0
The stone rocks        0     0   0
Tea is boiling         0     0   0
The bear drinks tea    1     0   1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM