基于条件修改NumPy数组值:原子键合邻接矩阵构建问题
原子键合邻接矩阵构建问题解决
你的问题核心是原子编号采用1起始规则,但NumPy数组索引是0起始,直接用原原子编号作为索引会导致位置错位,甚至触发索引越界错误(比如原子7对应数组第7位,但数组实际只有0-6共7个有效索引)。
修复循环代码
只需把原子编号减1,转换成0-based索引即可:
import pandas as pd import numpy as np d = {'atom1':[1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7], 'atom2':[2, 7, 3, 1, 6, 4, 2, 3, 5, 4, 6, 5, 7, 1, 6]} df = pd.DataFrame(d) array = np.zeros((7, 7), dtype=int) for i, row in df.iterrows(): a1 = row['atom1'] a2 = row['atom2'] # 转换为0-based索引 a1_idx = a1 - 1 a2_idx = a2 - 1 array[a1_idx, a2_idx] = 1 array[a2_idx, a1_idx] = 1 print(array)
运行后第一行会输出[0 1 0 0 0 0 1],对应原子1(索引0)与原子2(索引1)、原子7(索引6)的键合关系,完全符合你的预期。
更高效的向量化实现
如果处理的键合数据量较大,循环遍历效率偏低,可以用向量化操作一次性完成赋值:
import pandas as pd import numpy as np d = {'atom1':[1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7], 'atom2':[2, 7, 3, 1, 6, 4, 2, 3, 5, 4, 6, 5, 7, 1, 6]} df = pd.DataFrame(d) array = np.zeros((7, 7), dtype=int) # 提取原子编号并批量转换为0-based索引 atom1_idx = df['atom1'].values - 1 atom2_idx = df['atom2'].values - 1 # 批量赋值键合关系 array[atom1_idx, atom2_idx] = 1 array[atom2_idx, atom1_idx] = 1 print(array)
这种方法无需逐行遍历,执行速度更快,最终结果和循环版本完全一致。
内容的提问来源于stack exchange,提问作者Landon Gaber
相关产品推荐
相关产品推荐

