[英]Reading a numpy array of strings in memmap mode
I created this numpy array and stored it in disk as follows:我创建了这个 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()})
This works fine np.load('data.dat.npy')
这工作正常
np.load('data.dat.npy')
But, I want to use it in memmap mode.但是,我想在 memmap 模式下使用它。 So this fails
所以这失败了
np.load('data.dat.npy',mmap_mode='r')
ValueError: Array can't be memory-mapped: Python objects in dtype.
And this gives weird encoding这给出了奇怪的编码
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()
is a (200,) structured array.是一个 (200,) 结构化数组。
to load:装载:
In [152]: np.save('data.dat', {'data': data})
I have to use allow_pickle
:我必须使用
allow_pickle
:
In [157]: x=np.load('data.dat.npy',allow_pickle=True)
x
is () shaped object array. x
是 () 形对象数组。 That is x.item()
is a dictionary, containing the array as an element value.即
x.item()
是一个字典,包含数组作为元素值。
The problem lies with the save - it's saving a dictionary.问题在于保存 - 它正在保存一本字典。
In [161]: np.save('data.dat', data)
In [162]: x=np.load('data.dat.npy')
In [163]: x.shape
Out[163]: (200,)
now现在
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.