我在理解numpy.memmap
工作方式时遇到问题。背景是我需要numpy
通过删除条目来减少磁盘上保存的大型数组。读取数组并通过复制所需的部分来建立一个新的部分是行不通的——它只是不适合内存。所以这个想法是使用numpy.memmap
- 即在光盘上工作。她是我的代码(带有一个小文件):
import numpy
in_file = './in.npy'
in_len = 10
out_file = './out.npy'
out_len = 5
# Set up input dummy-file
dummy_in = numpy.zeros(shape=(in_len,1),dtype=numpy.dtype('uint32'))
for i in range(in_len):
dummy_in[i] = i + i
numpy.save(in_file, dummy_in)
# get dtype and shape from the in_file
in_npy = numpy.load(in_file)
in_dtype = in_npy.dtype
in_shape = (in_npy.shape[0],1)
del(in_npy)
# generate an 'empty' out_file with the desired dtype and shape
out_shape = (out_len,1)
out_npy = numpy.zeros(shape=out_shape, dtype=in_dtype)
numpy.save(out_file, out_npy)
del(out_npy)
# memmap both files
in_memmap = numpy.memmap( in_file, mode='r', shape=in_shape, dtype=in_dtype)
out_memmap = numpy.memmap(out_file, mode='r+', shape=out_shape, dtype=in_dtype)
print "in_memmap"
print in_memmap, "\n"
print "out_memmap before in_memmap copy"
print out_memmap, "\n"
# copy some parts
for i in range(out_len):
out_memmap[i] = in_memmap[i]
print "out_memmap after in_memmap copy"
print out_memmap, "\n"
out_memmap.flush()
# test
in_data = numpy.load(in_file)
print "in.npy"
print in_data
print in_data.dtype, "\n"
out_data = numpy.load(out_file)
print "out.npy"
print out_data
print out_data.dtype, "\n"
运行此代码,我得到:
in_memmap
[[1297436307]
[ 88400]
[ 662372422]
[1668506980]
[ 540682098]
[ 880098343]
[ 656419879]
[1953656678]
[1601069426]
[1701081711]]
out_memmap before in_memmap copy
[[1297436307]
[ 88400]
[ 662372422]
[1668506980]
[ 540682098]]
out_memmap after in_memmap copy
[[1297436307]
[ 88400]
[ 662372422]
[1668506980]
[ 540682098]]
in.npy
[[ 0]
[ 2]
[ 4]
[ 6]
[ 8]
[10]
[12]
[14]
[16]
[18]]
uint32
out.npy
[[0]
[0]
[0]
[0]
[0]]
uint32
形成输出很明显我做错了什么:
1) memmap
s 不包含数组中设置的值,in_memmap
并且out_memmap
包含相同的值。
2)不清楚复制命令是否将任何内容复制in_memmap
到out_memmap
(由于相同的值)。在调试模式下检查in_memmap[i]
和out_memmap[i]
我得到的值:memmap([1297436307], dtype=uint32)
。那么我可以像在代码中那样分配它们还是必须使用:out_memmap[i][0] = in_memmap[i][0]
?
3)out.npy
不会被操作更新为out_memmap
值flush()
。
谁能帮我理解我在这里做错了什么。
非常感谢