Python 以可读格式保存numpy数组字典
这不是一个重复的问题。我环顾四周发现,但是Python 以可读格式保存numpy数组字典,python,arrays,numpy,dictionary,Python,Arrays,Numpy,Dictionary,这不是一个重复的问题。我环顾四周发现,但是savez和pickle实用程序使文件无法被人读取。我想将它保存在一个.txt文件中,该文件可以加载回python脚本。因此,我想知道python中是否有一些实用程序可以简化这项任务并使编写的文件保持可读性 numpy数组字典包含2D数组 编辑: 据报道,我尝试了以下方法: import numpy as np W = np.arange(10).reshape(2,5) b = np.arange(12).reshape(3,4) d = {'W'
savez
和pickle
实用程序使文件无法被人读取。我想将它保存在一个.txt
文件中,该文件可以加载回python脚本。因此,我想知道python中是否有一些实用程序可以简化这项任务并使编写的文件保持可读性
numpy数组字典包含2D数组
编辑:据报道,我尝试了以下方法:
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)
这产生了以下错误:语法错误:解析时出现意外的EOF
但是,
out.txt
确实像预期的那样包含了字典。如何才能正确加载
编辑2:
遇到了一个问题:如果数组的大小很大,Craig的答案会截断数组。
out.txt
显示前几个元素,将中间元素替换为…
并显示最后几个元素。使用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()
将其读回并转换为字典:
或者,您可以直接从numpy
导入array
:
from numpy import array
f = open('out.txt', 'r')
data = f.read()
d = eval(data)
H/T:
处理大型阵列
默认情况下,numpy
汇总长度超过1000个元素的数组。您可以通过调用numpy.set\u 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:为什么不将字典转换成
pandas
dataframe,然后另存为pickle?pickle不会使书面内容不可读吗?什么东西不可读?人类不可读。为什么不json
?如何将其加载回另一个python脚本并检索单个2D numpy数组?@Craig这可能会起作用,当然,使用eval
的解决方案非常简洁。但是这正是您使用json
所能得到的,所以为什么不直接使用它呢?我尝试了这个,但在加载文件时出现了一个错误。我已经编辑了这个问题来展示它。如何正确加载字典?@ShraddheyaShendre我修复了加载时加载句柄numpy数组的代码。@AleksanderLidtke我得到TypeError:ndarray类型的对象在我尝试使用JSON时不可JSON序列化
。
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