Skip to main content
 首页 » 编程设计

python之numpy 数据类型 ValueError : invalid shape in fixed-type tuple之how can I get around it

2024年10月24日16zhengyun_ustc

我使用自定义数据类型,例如datatype = np.dtype('({:n},{:n})f4'.format(10000,100000)) 使用

从二进制文件中读取数据
np.fromfile(filename, dtype=datatype) 

但是,使用 np.dtype 定义数据类型会给大型数据集带来错误,如上面的示例数据类型所示:

ValueError: invalid shape in fixed-type tuple: dtype size in bytes must fit into a C int 

初始化那个大小的数组没有问题:a=np.zeros((10000,100000))。 所以我的问题是:这个限制从何而来,我该如何绕过它?我当然可以使用循环并一次读取 block ,但也许有更优雅的方法?

请您参考如下方法:

当您指定 '(M, N)f4' 的数据类型时,您实际上是在指定输出数组的最后两个维度,例如

np.zeros(5, np.dtype('(6, 7)f4')).shape 
# (5, 6, 7) 

您只需将数据读入一维数组,然后将其 reshape 为您想要的形状,即可获得相同的结果:

x = np.fromfile(filename, np.float32).reshape(-1, 10000, 100000)