优化内存使用 - 熊猫/ Python

问题描述 投票:0回答:2

我目前正在使用包含原始文本的数据集,我应该预先处理它:

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功能(数据集有很多拼写错误的单词)。

enter image description here

python pandas memory-management out-of-memory
2个回答
1
投票

我没有访问你的数据帧,所以这有点推测,但这里...

DataFrame.apply将立即在整个列上运行lambda函数,因此它可能在内存中保持进度。相反,您可以将lambda函数转换为预定义函数并使用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)
   # ...

你可以尝试一下,看看它有帮助吗?


1
投票

无论如何,我会使用dask,您可以将数据帧划分为块(分区),然后您可以检索每个部分并使用它。

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

© www.soinside.com 2019 - 2024. All rights reserved.