优化内存使用 - 熊猫/ Python

时间:2018-02-28 13:46:17

标签: python pandas memory-management out-of-memory

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

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

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

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

相关问题