【问题标题】:Most efficient way of storing dictionary consisting dataframes存储包含数据帧的字典的最有效方法
【发布时间】:2020-04-09 15:10:38
【问题描述】:

我有一个包含数据框的字典。

dictionary = {"key1": df1,
              "key2": df2, and so on...}

很少有 stackoverflow 帖子和 reddit 建议使用 Json 模块和 pickle 模块。

什么是最有效的方法,为什么?

当我将小字典转换为 pickle 时,它​​的内存小于 0kb,它会呈现 EOFError: Ran out of input,此处解释为 Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

【问题讨论】:

  • 使用泡菜。您可能无法将数据帧的所有可能数据存储在 json 中
  • jsonpickle 是另一种选择

标签: python pandas pickle


【解决方案1】:

如果您喜欢紧凑的文件格式,我建议您使用 pickle。

# import packages
import pandas as pd
import numpy as np
import pickle
import os

# create dictionary of dataframes
nrows, ncols, ndataframes = 1_000, 50, 100
my_dict = {k:v for (k,v) in [[f'df_{n}', pd.DataFrame(np.random.rand(nrows, ncols))] for n in range(ndataframes)]}

# save dictionary as pickle file
pickle_out = open('my_dict.pickle', 'wb')
pickle.dump(my_dict, pickle_out)
pickle_out.close()

# create new dictionary from pickle file
pickle_in = open('my_dict.pickle', 'rb')
new_dict = pickle.load(pickle_in)

# print file size
print('File size pickle file is', round(os.path.getsize('my_dict.pickle') / (1024**2), 1), 'MB')

# sample
new_dict['df_10'].iloc[:5, :5]

结果:

File size pickle file is 38.2 MB

          0         1         2         3         4
0  0.338838  0.501158  0.406240  0.693233  0.567305
1  0.092142  0.569312  0.952694  0.083705  0.006950
2  0.684314  0.373091  0.550300  0.391419  0.877889
3  0.117929  0.597653  0.726894  0.763094  0.466603
4  0.530755  0.472033  0.553457  0.863435  0.906389

【讨论】:

  • 谢谢!我正在测试小字典,但是在 new_dict = pickle.load(pickle_in) 中它给出 EOFError: Ran out of input
  • 你能检查一下你的pickle文件是否成功写入磁盘(并且文件大小> 0字节)。
  • 当你可以分享你的代码时,我会看看。我的答案中的代码使用 Python 3.6.9 在我的机器上运行没有问题
  • 我刚刚创建了一个两个数据框,每个数据框有 3 行。即使它有两个 3x5 df,它也有 0kb。
  • 您能否将代码添加到您的问题中。我怀疑读取泡菜失败是因为保存泡菜文件不成功。
【解决方案2】:

另一种选择可能是 HDFStore,它是一个类似 dict 的对象,它使用高性能 HDF5 格式读取和写入 pandas,更多详细信息请参见:http://pandas-docs.github.io/pandas-docs-travis/user_guide/io.html#hdf5-pytables

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2013-06-16
    • 2011-01-05
    相关资源
    最近更新 更多