考虑这个例子:
import numpy as np
a = np.array(1)
np.save("a.npy", a)
a = np.load("a.npy", mmap_mode='r')
print(type(a))
b = a + 2
print(type(b))
哪个输出
<class 'numpy.core.memmap.memmap'>
<class 'numpy.int32'>
因此,这似乎b
不再是 amemmap
了,我认为这会迫使numpy
阅读整体a.npy
,从而违背了 memmap 的目的。因此我的问题是,可以将操作memmaps
推迟到访问时间吗?
我相信子类化ndarray
或memmap
可以工作,但对我的 Python 技能没有足够的信心来尝试它。
这是一个显示我的问题的扩展示例:
import numpy as np
# create 8 GB file
# np.save("memmap.npy", np.empty([1000000000]))
# I want to print the first value using f and memmaps
def f(value):
print(value[1])
# this is fast: f receives a memmap
a = np.load("memmap.npy", mmap_mode='r')
print("a = ")
f(a)
# this is slow: b has to be read completely; converted into an array
b = np.load("memmap.npy", mmap_mode='r')
print("b + 1 = ")
f(b + 1)