np.memmap读取大文件

Numpy中的ndarray是一种新形式的Python内建类型。因此,它可以在需要时被继承。ndarray形成了许多有用类的基础。
np.memmap就是其中一种,它是内存映射文件。本质上就是使用C语言中的fseek随机访问文件的任何一个位置执行读写操作。当一个特别大的数组无法常驻内存时,np.memmap非常有用。

参数类型:

  • filename:字符串、文件或者path
  • dtype:默认为uint8,表示每个字节
  • mode:支持r+,r,w+,c四种文件打开方式,r表示只读方式打开文件爱你,r+表示可读可写,w+表示先覆盖一个已存在的文件然后可读可写,c表示可以对文件进行修改但是不会保存到磁盘。默认为r+。
  • offset:表示数组数据在文件中的偏移,此值应该是dtype类型的大小的整数倍。
  • shape:可以指定数组的维度,默认是一维数组。

memmap默认的文件打开方式是r+。

import numpy as np

a = np.random.randint(0, 10, (3, 4), dtype=np.int32)
print(a)
a.tofile("haha.bin")
b = np.memmap("haha.bin", dtype=np.int32, shape=(3, 4))
print(b)
b[0, 0] = 100
del b  # 关闭文件,自动调用数组的finalize函数
b = np.memmap("haha.bin", dtype=np.int32, shape=(3, 4))
print(b)

输出为:

[[7 7 7 3]
 [9 3 7 9]
 [0 7 8 8]]
[[7 7 7 3]
 [9 3 7 9]
 [0 7 8 8]]
[[100   7   7   3]
 [  9   3   7   9]
 [  0   7   8   8]]

numpy数组和bytes互转

import numpy as np

a = np.random.rand(3, 3).astype(np.float32)
print(a)
b = a.tobytes()
res = np.frombuffer(b, dtype=np.float32)
print(res)

参考资料

https://docs.scipy.org/doc/numpy/reference/arrays.classes.html

原文地址:https://www.cnblogs.com/weiyinfu/p/10740529.html