小编典典

pandas数据框内存python

python

我想将稀疏矩阵(156060x11780)转换为数据帧,但出现内存错误,这是我的代码

vect = TfidfVectorizer(sublinear_tf=True, analyzer='word', 
                       stop_words='english' , tokenizer=tokenize,
                       strip_accents = 'ascii')

X = vect.fit_transform(df.pop('Phrase')).toarray()

for i, col in enumerate(vect.get_feature_names()):
    df[col] = X[:, i]

我有一个问题 X = vect.fit_transform(df.pop('Phrase')).toarray()。我该如何解决?


阅读 220

收藏
2020-12-20

共1个答案

小编典典

尝试这个:

from sklearn.feature_extraction.text import TfidfVectorizer
vect = TfidfVectorizer(sublinear_tf=True, analyzer='word', stop_words='english',
                       tokenizer=tokenize,
                       strip_accents='ascii',dtype=np.float16)
X = vect.fit_transform(df.pop('Phrase'))  # NOTE: `.toarray()` was removed


for i, col in enumerate(vect.get_feature_names()):
    df[col] = pd.SparseSeries(X[:, i].toarray().reshape(-1,), fill_value=0)

更新: 对于Pandas 0.20+,我们可以SparseDataFrame直接从稀疏数组构造:

from sklearn.feature_extraction.text import TfidfVectorizer
vect = TfidfVectorizer(sublinear_tf=True, analyzer='word', stop_words='english',
                       tokenizer=tokenize,
                       strip_accents='ascii',dtype=np.float16)

df = pd.SparseDataFrame(vect.fit_transform(df.pop('Phrase')),
                        columns=vect.get_feature_names(),
                        index=df.index)
2020-12-20