使用numpy中的savez(save)保存非数组数据

savez()保存非数组数据时,如字符串,字典时,会转换为object,此时不能直接像读取数组那样直接用load读出后索引,可以通过加[()]解决。例如:

import numpy as np

str = 'abc'
arr = np.array([[1, 2], [3, 4]])
dict = {'a' : 1, 'b': 2}
np.savez('data.npz', str= str, arr= arr, dict= dict)

data = np.load('data.npz')
str = data['str']
arr = data['arr']
dict = data['dict']
print(dict['a'])

运行会出如下错误:

"C:\Program Files (x86)\Python35-32\python.exe" "D:/test/test.py"
Traceback (most recent call last):
  File "D:/test/test.py", line 12, in 
    print(dict['a'])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Process finished with exit code 1

将data[‘str‘’]和data[‘dict’]改为data[‘str’][()]和data[‘dict’][()]就不会出错了。
--------------------- 
作者:苗小熊 
来源:https://blog.csdn.net/miao20091395/article/details/79094389 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(Python)