簡體   English   中英

優化內存使用-Pandas / Python

[英]Optimizing memory usage - Pandas/Python

我目前正在使用包含原始文本的數據集,應對其進行預處理:

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize 
from nltk.stem import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer

stop_words = set(stopwords.words('english'))
stemmer = SnowballStemmer('english')
lemma = WordNetLemmatizer()

from autocorrect import spell

for df in [train_df, test_df]:
    df['comment_text'] = df['comment_text'].apply(lambda x: word_tokenize(str(x)))
    df['comment_text'] = df['comment_text'].apply(lambda x: [lemma.lemmatize(spell(word)) for word in x])
    df['comment_text'] = df['comment_text'].apply(lambda x: ' '.join(x))

但是,包括spell功能在內會增加內存使用量,直到出現“內存錯誤”為止。 不使用此類功能就不會發生這種情況。 我想知道是否有一種方法可以優化此過程,保持spell功能(數據集包含很多拼寫錯誤的單詞)。

在此處輸入圖片說明

我沒有訪問您的數據框,所以這有點投機,但是這里...

DataFrame.apply將立即在整個列上運行lambda函數,因此它可能會將進度保存在內存中。 相反,您可以將lambda函數轉換為預定義的函數,並改用DataFrame.map ,它以DataFrame.map元素方式應用該函數。

def spellcheck_string(input_str):
    return [lemma.lemmatize(spell(word)) for word in x]

for df in [train_df, test_df]:
   # ...
    df['comment_text'] = df['comment_text'].map(spellcheck_string)
   # ...

您可以嘗試一下,看看是否有幫助?

無論如何,我將使用dask進行工作,您可以將數據划分為多個塊(分區),然后可以檢索每個部分並使用它。

https://dask.pydata.org/en/latest/dataframe.html

暫無
暫無

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

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