numpy 文件的存储与读取

一时失言乱红尘 2022-02-20 13:48 365阅读 0赞

需要了解两个函数名: tofile 和 fromfile 两个函数。tofile输出的数据没有格式,因此用numpy.fromfile读回来的时候需要自己格式化数据。

  1. a = np.arange(0,12)
  2. >>> a
  3. array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  4. >>> a.shape=3,4
  5. >>> a
  6. array([[ 0, 1, 2, 3],
  7. [ 4, 5, 6, 7],
  8. [ 8, 9, 10, 11]])
  9. >>> a.tofile("a.bin")
  10. >>> b=np.fromfile("a.bin",dtype=np.float)
  11. >>> b
  12. array([2.12199579e-314, 6.36598737e-314, 1.06099790e-313, 1.48539705e-313,
  13. 1.90979621e-313, 2.33419537e-313])
  14. >>> a.dtype
  15. dtype('int32')
  16. >>> b=np.fromfile("a.bin",dtype=np.int32)
  17. >>> b
  18. array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  19. >>> b.shape=3,4
  20. >>> b
  21. array([[ 0, 1, 2, 3],
  22. [ 4, 5, 6, 7],
  23. [ 8, 9, 10, 11]])

numpy.load和numpy.save函数以NumPy专用的二进制类型保存数据,这两个函数会自动处理元素类型和shape等信息,使用它们读写数组就方便多了,但是numpy.save输出的文件很难和其它语言编写的程序读入:

  1. >>> np.save("a.npy",a)
  2. >>> c=np.load("a.npy")
  3. >>> c
  4. array([[ 0, 1, 2, 3],
  5. [ 4, 5, 6, 7],
  6. [ 8, 9, 10, 11]])

文件名和文件对象:

  1. >>> a=np.arange(8)
  2. >>> b=np.add.accumulate(a)
  3. >>> c=a+b
  4. >>> c
  5. array([ 0, 2, 5, 9, 14, 20, 27, 35])
  6. >>> a
  7. array([0, 1, 2, 3, 4, 5, 6, 7])
  8. >>> b
  9. array([ 0, 1, 3, 6, 10, 15, 21, 28], dtype=int32)
  10. >>> f=file("result.npy","wb")
  11. Traceback (most recent call last):
  12. File "<pyshell#37>", line 1, in <module>
  13. f=file("result.npy","wb")
  14. NameError: name 'file' is not defined
  15. >>> f=open("result.npy","wb")
  16. >>> np.save(f,a)
  17. >>> np.save(f,b)
  18. >>> np.save(f,c)
  19. >>> f.close()
  20. >>> f=open("result.npy","rb")
  21. >>> np.load(f)
  22. array([0, 1, 2, 3, 4, 5, 6, 7])
  23. >>> np.load(f)
  24. array([ 0, 1, 3, 6, 10, 15, 21, 28])
  25. >>> np.load(f)
  26. array([ 0, 2, 5, 9, 14, 20, 27, 35])

参考:numpy 快速处理数据

发表评论

表情:
评论列表 (有 0 条评论,365人围观)

还没有评论,来说两句吧...

相关阅读