假设我有大量 NumPy 数组保存为文件(np.save(),“.npy”文件)。所有这些都有形状,例如(n,20),我不打开文件就不知道n。 n 每个文件都不同。
我想将这些合并为一个数据集,然后使用一组选择方法将其拆分为三个不同的 numpy 数组写入磁盘。
通常我会遍历所有文件并使用np.concatenate()。然而,最终的数组很可能不适合内存。
我的另一个选择是使用 np.memmap(),我完全不确定它是如何工作的。据我了解,我必须这样做:
a = np.memmap('output.npy',dtype='float64',mode='w+',shape=(N,20))
for i,f in enumerate(myfiles):
a[i,:] = np.load(f)
a.flush()
# And then find a way to split "a" into three, does the following work?
part_one = a[ [0,2,10,42,58] , : ]
问题是我不知道 N,即最终的行数。因此,我需要打开每个文件,读取行数,关闭文件,在声明 memmap 之前对所有行数求和。这是非常低效的,必须有更好的方法。
你对这个问题有什么建议吗?我做错了什么吗?
请您参考如下方法:
.npy file specification定义 npy 文件的 header 。我找不到阅读它的现成方法,但格式很简单,您可以自己提取信息。文件信息被编码在一个包含 shape 元组的 python dict 中。这是对文件顶部的简短读取,比读取数据要快得多。
import struct
import ast
# structs to decode .npy file header consisting of a "magic"
# string verifying the file type, major and minor version numbers,
# header length, and literal string representation of a python dict
# holding file's type and shape.
npy_magic = b"\x93NUMPY"
npy_v1_header = struct.Struct(
"<" # little-endian encoding
"6s" # 6 byte magic string
"B" # 1 byte major number
"B" # 1 byte minor number
"H" # 2 byte header length
# ... header string follows
)
npy_v2_header = struct.Struct(
"<" # little-endian encoding
"6s" # 6 byte magic string
"B" # 1 byte major number
"B" # 1 byte minor number
"L" # 4 byte header length
# ... header string follows
)
def read_npy_file_header(filename):
with open(filename, 'rb') as fp:
buf = fp.read(npy_v1_header.size)
magic, major, minor, hdr_size = npy_v1_header.unpack(buf)
if magic != npy_magic:
raise IOError("Not an npy file")
if major not in (0,1):
raise IOError("Unknown npy file version")
if major == 2:
fp.seek(0)
buf = fp.read(npy_v2_header.size)
magic, major, minor, hdr_size = npy_v2_header.unpack(buf)
return ast.literal_eval(fp.read(hdr_size).decode('ascii'))
# test
from glob import glob
for fn in glob('*.npy'):
print(fn, read_npy_file_header(fn))
