python - 保存按键排序的类似 Shelf Dictionary 的对象

标签 python ordereddictionary shelve

我有一个很大的字典 100 000 个键和大型 numpy 数组作为值。我想将其另存为文件以便更快加载。

我尝试将其转储为泡菜,但内存不足。然后尝试了 json.dump 但不支持 Numpy 数组作为值。

最后我尝试使用货架,但无法按顺序保存。

我有以下代码:

with closing(shelve.open('file1.shelf', 'c')) as f:
     for id in ids:
         f[id] = np.array().shape(300, 27, 3)

我想按照 id 的顺序保存类似于字典的架子对象。所以我想按 id 排序然后将其另存为文件。 我可以在架子对象上使用 OrderedDict 还是应该使用其他方法来解决这个特定问题?

img_dic = collections.OrderedDict(sorted(f.items()))

谢谢!

最佳答案

您是否尝试过从 numpy 数组字典创建 Numpy Dataframe?字典的键可以是索引列。 Dataframe 有多种方式保存到磁盘中。

也许那里的to_pickle方法更有效。 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_pickle.html

否则,您可以另存为 parquet 文件或多种其他格式

关于python - 保存按键排序的类似 Shelf Dictionary 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53834373/

相关文章:

python - 如何降低 matplotlib 中的孵化密度

python - Python 中 Json 到 OrderedDict

python - 将 Python 列表转换为有序的唯一值

python - 在数据库中存储 700 万个键的 python 字典

perforce - 我可以更新由其他用户创建的 p4 搁置吗?

python - 使用Python Shelf存储字典对象

python - 应用引擎 : CPU Over Quota on urlfetch()

Python subprocess.popen 在与子进程交互时失败

python - 在给定股票列表的循环中创建不同的数据框

python - 在 Python 3 中使用 DictReader 时,如何查找字典中行的最小值和最大值