[英]Reading a numpy array of strings in memmap mode
我创建了这个 numpy 数组并将其存储在磁盘中,如下所示:
s = (b'foo', b'bar', b'baz', b'buzz')
def build_numpy_array():
return np.fromiter((s for _ in range(200)), dtype=[('foo','S40'),
('bar', 'S40'), ('baz', 'S40'),
('buzz', 'S40')
])
np.save('data.dat', {'data': build_numpy_array()})
这工作正常np.load('data.dat.npy')
但是,我想在 memmap 模式下使用它。 所以这失败了
np.load('data.dat.npy',mmap_mode='r')
ValueError: Array can't be memory-mapped: Python objects in dtype.
这给出了奇怪的编码
np.memmap('data.dat.npy', mode='r',dtype=[('foo','S40'),
('bar', 'S40'), ('baz', 'S40'),
('buzz', 'S40')
])
(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00bar', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00baz', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00buz', b'z\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00foo')
data = build_numpy_array()
是一个 (200,) 结构化数组。
装载:
In [152]: np.save('data.dat', {'data': data})
我必须使用allow_pickle
:
In [157]: x=np.load('data.dat.npy',allow_pickle=True)
x
是 () 形对象数组。 即x.item()
是一个字典,包含数组作为元素值。
问题在于保存 - 它正在保存一本字典。
In [161]: np.save('data.dat', data)
In [162]: x=np.load('data.dat.npy')
In [163]: x.shape
Out[163]: (200,)
现在
In [165]: r = np.load('data.dat.npy',mmap_mode='r')
In [166]: r
Out[166]:
memmap([(b'foo', b'bar', b'baz', b'buzz'),
(b'foo', b'bar', b'baz', b'buzz'),
(b'foo', b'bar', b'baz', b'buzz'),
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.