gpt4 book ai didi

python - 将数据帧酸洗到磁盘时出现内存错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:27 25 4
gpt4 key购买 nike

我有一个只有二进制(1 或 0)值的 51K X 8.5K 数据框。

我写了下面的代码:

将数据提取到磁盘

outfile=open("df_preference.p", "wb")
pickle.dump(df_preference,outfile)
outfile.close()

它抛出如下内存错误:

MemoryError                               Traceback (most recent call last)
<ipython-input-48-de66e880aacb> in <module>()
2
3 outfile=open("df_preference.p", "wb")
----> 4 pickle.dump(df_preference,outfile)
5 outfile.close()

我假设这意味着这个数据很大而且不能 pickle?但它只有二进制值。

在此之前,我从另一个具有正常计数和大量零的数据框中创建了这个数据集。使用了以下代码:

df_preference=df_recommender.applymap(lambda x: np.where(x >0, 1, 0))

这本身就花了一些时间来创建 df_preference。矩阵大小相同。

我担心的是,如果使用 applymap 创建数据框需要时间,并且 ii) 由于内存错误甚至没有 pickle 数据框,那么继续我需要使用 SVD 和交替最小值对这个 df_prefence 进行矩阵分解广场。那它会更慢吗?如何解决这个缓慢的运行并解决内存错误?

谢谢

最佳答案

更新:

对于 10 值,您可以使用 int8(1 字节)dtype,这将减少至少 4 的内存使用次。

(df_recommender > 0).astype(np.int8).to_pickle('/path/to/file.pickle')

这是一个 51K x 9K 数据帧的例子:

In [1]: df = pd.DataFrame(np.random.randint(0, 10, size=(51000, 9000)))

In [2]: df.shape
Out[2]: (51000, 9000)

In [3]: df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 51000 entries, 0 to 50999
Columns: 9000 entries, 0 to 8999
dtypes: int32(9000)
memory usage: 1.7 GB

源DF需要1.7GB内存

In [6]: df_preference = (df>0).astype(int)

In [7]: df_preference.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 51000 entries, 0 to 50999
Columns: 9000 entries, 0 to 8999
dtypes: int32(9000)
memory usage: 1.7 GB

生成的 DF 再次需要 1.7 GB 的内存

In [4]: df_preference = (df>0).astype(np.int8)

In [5]: df_preference.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 51000 entries, 0 to 50999
Columns: 9000 entries, 0 to 8999
dtypes: int8(9000)
memory usage: 437.7 MB

使用 int8 dtype 只需要 438 MB

现在让我们将它保存为 Pickle 文件:

In [10]: df_preference.to_pickle('d:/temp/df_pref.pickle')

文件大小:

{ temp }  » ls -lh df_pref.pickle
-rw-r--r-- 1 Max None 438M May 28 09:20 df_pref.pickle

旧答案:

试试这个:

(df_recommender > 0).astype(int).to_pickle('/path/to/file.pickle')

解释:

In [200]: df
Out[200]:
a b c
0 4 3 3
1 1 2 1
2 2 1 0
3 2 0 1
4 2 0 4

In [201]: (df>0).astype(int)
Out[201]:
a b c
0 1 1 1
1 1 1 1
2 1 1 0
3 1 0 1
4 1 0 1

PS 您可能还想将 DF 保存为 HDF5 文件而不是 Pickle - 参见 this comparison详情

关于python - 将数据帧酸洗到磁盘时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37493165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com