以人类可读的格式保存numpy数组的字典

时间:2017-04-14 01:32:26

标签: python arrays numpy dictionary

这是不是重复的问题。我环顾了很多,发现this question,但savezpickle实用程序使人无法读取该文件。我想将它保存在.txt文件中,该文件可以加载回python脚本。所以我想知道python中是否有一些实用程序可以帮助完成这项任务并保持人类可读的文件。

numpy数组字典包含2D数组。

编辑:
根据{{​​3}},我尝试了以下内容:

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: 遇到问题:如果大小很大,Craig的答案会截断数组。 out.txt显示前几个元素,用...替换中间元素,并显示最后几个元素。

1 个答案:

答案 0 :(得分:2)

使用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)

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

from numpy import array

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

H / T: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

H / T:Ellipses when converting list of numpy arrays to string in python 3