numpy.memmap
数组上的哪些索引操作返回内存中的副本,而不是仍然由文件支持的视图? 文档没有解释哪些索引操作是“安全的”。
np.memmap
对象与其他 np.ndarray
对象具有相同的复制与查看行为,如此处所述。
特别是,使用切片对象的切片返回视图,而使用其他数组的“高级索引”返回副本。一个奇怪的怪癖是,如果您使用高级索引来分配内容,它确实工作。
import numpy as np
memmap = np.memmap(
"/tmp/test.npy", dtype="float32", mode="w+", shape=(10, 10)
)
# operations which create a view of the memmap
print(f"Regular slicing: {type(memmap[:5])}") # numpy.memmap
print(f"Slice with slice object: {type(memmap[np.s_[2::2]])}") # numpy.memmap
# operations which create an in-memory copy
print(f"Slice with np array: {type(memmap[np.arange(5)])}") # numpy.ndarray
print(f"Type when we slice with list: {type(memmap[[0]])}") # numpy.ndarray
# writing to a copy does not affect the original memmap
ndarray = memmap[np.arange(5)]
ndarray[:] = 1
assert np.allclose(memmap[:5], 0)
# quirk: writing using a list works if we don't bind to a new variable
memmap[[0, 1, 2, 3, 4]] = 1
assert np.allclose(memmap[:5], 1)