numpy数组重塑报错:无法将大小为0的数组转为(36668,132)形状
问题
我有多个包含不同类的Python文件,其中两个文件负责读取文本文件并计算,将结果存入列表后转为numpy数组,再重塑为(36668,132)的2D数组并保存为.npy文件,供其他类按特定方式索引。单独运行这两个类时没有报错,但整合所有类运行时,出现错误:ValueError: cannot reshape array of size 0 into shape (36668,132)。奇怪的是,如果把所有类合并到一个文件,并在被其他类调用前返回该numpy数组,重塑操作就能正常执行。
数组生成及重塑的核心代码:
for k in range(0, len(self.coords)): for i in range(0, len(self.topology)): if len(self.topology[i]) == 2: self.bat_file1.append(self.bond_length((self.coords[k][self.topology[i][0] - 1]), (self.coords[k][self.topology[i][1] -1]))) # 其他相关计算逻辑(格式正确,此处为简化粘贴) self.bat_file1 = np.array(self.bat_file1) self.bat_file1 = np.reshape(self.bat_file1,(36668,132)) return np.save('./bat_coords.npy',self.bat_file1)
其他文件中调用该模块的代码:
def get_top(self): self.non_redundant_paths = self.get_paths() self.temp2 = self.non_redundant_paths self.non_redundant_paths = self.edit_file(self.non_redundant_paths) f = open("./top_new", "w+") f.write(self.non_redundant_paths) bat = GETBAT1.GET_BAT("./top_new","./Cope_TS_part_BOMD_p1_36668.xyz") bat.read_topology() self.bat_coords = bat.read_topology() ent = ENTROPY1.Entropy("./bat_coords.npy") self.bat_coords = self.bat_coords.T
GETBAT1和ENTROPY1都是导入的模块,我不理解为什么调用bat.read_topology()时会出现数组大小为0的错误,希望得到解决方法。
解决思路与方法
修复重复调用
read_topology()的问题
你连续调用了两次bat.read_topology():bat.read_topology() self.bat_coords = bat.read_topology()如果
read_topology()的逻辑是第一次执行填充self.bat_file1,第二次执行时没有重新读取/计算(比如内部状态未重置),就会导致第二次调用时self.bat_file1为空列表,转成数组后大小为0。只需保留一次调用并接收返回值:self.bat_coords = bat.read_topology()验证文件读取的有效性
整合运行时,文件路径、权限或内容格式可能出现问题,导致self.coords或self.topology为空。在GET_BAT类的read_topology()方法开头添加检查:import os print(f"Topology文件存在: {os.path.exists('./top_new')}") print(f"XYZ文件存在: {os.path.exists('./Cope_TS_part_BOMD_p1_36668.xyz')}") print(f"Coords长度: {len(self.coords)}, Topology长度: {len(self.topology)}")若输出显示文件不存在或长度为0,需排查文件路径是否正确、读取逻辑是否有误。
重置类的内部状态
确保每次调用read_topology()时,self.bat_file1都会被重新初始化为空列表,避免残留之前的空状态:def read_topology(self): self.bat_file1 = [] # 每次调用重置列表 # 后续循环计算逻辑...提前校验元素数量
在重塑数组前,先检查列表元素总数是否等于36668*132=4840176,提前定位问题:print(f"bat_file1元素数量: {len(self.bat_file1)}") self.bat_file1 = np.array(self.bat_file1) if len(self.bat_file1) != 36668*132: raise ValueError(f"预期{36668*132}个元素,实际得到{len(self.bat_file1)}个") self.bat_file1 = np.reshape(self.bat_file1,(36668,132))
内容的提问来源于stack exchange,提问作者ira_s16

