【问题标题】:Saving a dictionary of numpy arrays in human-readable format以人类可读的格式保存 numpy 数组的字典
【发布时间】:2017-04-14 01:32:26
【问题描述】:

不是重复的问题。我环顾四周,发现this question,但savezpickle 实用程序使文件无法被人类读取。我想将它保存在一个 .txt 文件中,该文件可以加载回 python 脚本。所以我想知道python中是否有一些实用程序可以促进这项任务并保持书面文件可供人类阅读。

numpy 数组字典包含二维数组。

编辑:
根据Craig's answer,我尝试了以下方法:

import numpy as np 

W = np.arange(10).reshape(2,5)
b = np.arange(12).reshape(3,4)
d = {'W':W, 'b':b}
with open('out.txt', 'w') as outfile:
    outfile.write(repr(d))

f = open('out.txt', 'r')
d = eval(f.readline())

print(d) 

这给出了以下错误:SyntaxError: unexpected EOF while parsing
但是out.txt确实包含预期的字典。如何正确加载?

编辑 2: 遇到一个问题:如果大小很大,克雷格的答案会截断数组。 out.txt 显示前几个元素,用... 替换中间元素并显示最后几个元素。

【问题讨论】:

  • 为什么不把字典变成pandas数据框,然后另存为pickle?
  • pickle不会让写出来的内容不可读吗?
  • 什么无法读取?
  • @splinter - 人类无法阅读。
  • 为什么不json

标签: python arrays numpy dictionary


【解决方案1】:

使用 repr() 将 dict 转换为字符串并将其写入文本文件。

import numpy as np

d = {'a':np.zeros(10), 'b':np.ones(10)}
with open('out.txt', 'w') as outfile:
    outfile.write(repr(d))

您可以使用eval() 将其读回并转换为字典:

import numpy as np

f = open('out.txt', 'r')
data = f.read()
data = data.replace('array', 'np.array')
d = eval(data)

或者,你可以直接从numpy导入array

from numpy import array

f = open('out.txt', 'r')
data = f.read()
d = eval(data)

电话:How can a string representation of a NumPy array be converted to a NumPy array?

处理大型数组

默认情况下,numpy 汇总超过 1000 个元素的数组。您可以通过调用numpy.set_printoptions(threshold=S) 更改此行为,其中S 大于数组的大小。例如:

import numpy as np 

W = np.arange(10).reshape(2,5)
b = np.arange(12).reshape(3,4)
d = {'W':W, 'b':b}

largest = max(np.prod(a.shape) for a in d.values()) #get the size of the largest array
np.set_printoptions(threshold=largest) #set threshold to largest to avoid summarizing

with open('out.txt', 'w') as outfile:
    outfile.write(repr(d))    

np.set_printoptions(threshold=1000) #recommended, but not necessary

电话:Ellipses when converting list of numpy arrays to string in python 3

【讨论】:

  • 如何将其加载回另一个 python 脚本并检索单个 2D numpy 数组?
  • @Craig 这可以工作,当然,eval 的解决方案很简洁。但这正是您使用 json 所得到的,那么为什么不直接使用它呢?
  • 我试过这个,但是在加载文件时出错了。我已经编辑了问题以显示它。如何正确加载字典?
  • @ShraddheyaShendre 我修复了加载处理 numpy 数组的代码。
  • @AleksanderLidtke 当我尝试使用 JSON 时,我得到了TypeError: Object of type 'ndarray' is not JSON serializable
猜你喜欢
  • 2018-04-18
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 2017-02-15
相关资源
最近更新 更多