编程语言
首页 > 编程语言> > python-熊猫:将系列字典保存到磁盘

python-熊猫:将系列字典保存到磁盘

作者:互联网

我有python pandas系列字典:

id           dicts
1            {'5': 1, '8': 20, '1800': 2}
2            {'2': 2, '8': 1, '1000': 25, '1651': 1}
...          ...
...          ...
...          ...
20000000     {'2': 1, '10': 20}

词典中的(键,值)表示(“功能”,计数).存在大约2000个独特功能.

该系列在熊猫中的内存使用量约为500MB.
将对象写入磁盘的最佳方法是什么(理想情况下,磁盘空间使用率较低,并且写入后又回读很快)?

考虑的选项(并尝试了前两个):
-to_csv(但将字典视为字符串,因此之后转换回字典非常慢)
-cPickle(但在执行过程中用尽了内存)
-转换为稀疏的稀疏矩阵结构

解决方法:

我很好奇您的系列如何仅占用500MB.如果使用的是.memory_usage方法,则此方法将仅返回每个python对象引用所使用的总内存,这是Series系列存储的所有内容.那不算字典的实际记忆.粗略计算20,000,000 * 288字节= 5.76GB应该是您的内存使用量. 288字节是每个字典所需内存的保守估计.

转换为稀疏矩阵

无论如何,请尝试以下方法将数据转换为稀疏矩阵表示形式:

import numpy as np, pandas as pd
from sklearn.feature_extraction import DictVectorizer
from scipy.sparse import csr_matrix
import pickle

我将使用整数而不是字符串作为键,因为这将在以后保持正确的顺序.因此,假设您的系列名为dict_series:

dict_series = dict_series.apply(lambda d: {int(k):d[k] for k in d}

这可能会占用大量内存,并且从一开始就使用int作为键来创建您的系列字典可能会更好.或者只是您可以跳过此步骤.现在,构建您的稀疏矩阵:

dv = DictVectorizer(dtype=np.int32)
sparse = dv.fit_transform(dict_series)

保存到磁盘

现在,基本上,您可以从3个字段重建稀疏矩阵:sparse.data,sparse.indices,sparse.indptr(可选)sparse.shape.保存数组sparse.data,sparse.indices,sparse.indptr数组的最快,最节省内存的方法是使用np.ndarray tofile方法,该方法将数组保存为原始字节.从documentation开始:

This is a convenience function for quick storage of array data.
Information on endianness and precision is lost, so this method is not
a good choice for files intended to archive data or transport data
between machines with different endianness.

因此,此方法会丢失任何dtype信息和固有性.可以通过简单地事先记下数据类型来解决前一个问题,无论如何,您都将使用np.int32.如果您在本地工作,那么后一个问题就不成问题,但是如果可移植性很重要,则需要研究存储信息的其他方式.

# to save
sparse.data.tofile('data.dat')
sparse.indices.tofile('indices.dat')
sparse.indptr.tofile('indptr.dat')
# don't forget your dict vectorizer!
with open('dv.pickle', 'wb') as f:
    pickle.dump(dv,f) # pickle your dv to be able to recover your original data!

要恢复一切:

with open('dv.pickle', 'rb') as f:
    dv = pickle.load(f)

sparse = csr_matrix((np.fromfile('data.dat', dtype = np.int32),
                     np.fromfile('indices.dat', dtype = np.int32),
                     np.fromfile('indptr.dat', dtype = np.int32))

original = pd.Series(dv.inverse_transform(sparse))

标签:pandas,scipy,sparse-matrix,dictionary,python
来源: https://codeday.me/bug/20191118/2027581.html