优化内存使用 - 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 函数会增加内存使用量,直到我得到 "Memory error"。如果不使用此类功能,就不会发生这种情况。我想知道是否有一种方法可以优化此过程并保持 spell 函数(数据集有很多拼写错误的单词)。

我无法访问您的数据框,所以这有点推测,但这里...

DataFrame.apply 将 运行 立即在整个列上执行 lambda 函数,因此它可能会保留内存中的进度。相反,您可以将 lambda 函数转换为 pre-defined 函数并改用 DataFrame.map,这会应用函数 element-wise。

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