如何用NumPy meshgrid实现中心元组与ts变量的配对网格?
问题描述
现有如下numpy变量:
centers = np.array([(2.78568, 0.0000), (4.32842, -0.775169), (7.43238, -1.000000)]) ts = np.array([0.1, 0.2, 0.3])
需要生成一个网格组合,要求centers中的每个坐标元组保持配对,再与ts中的每个元素进行组合,最终得到如下形式的输出:
| sigma | tau | t |
|---|---|---|
| 2.78568 | 0.000000 | 0.1 |
| 4.32842 | -0.775169 | 0.1 |
| 7.43238 | -1.000000 | 0.1 |
| 2.78568 | 0.000000 | 0.2 |
| 4.32842 | -0.775169 | 0.2 |
| 7.43238 | -1.000000 | 0.2 |
| 2.78568 | 0.000000 | 0.3 |
| 4.32842 | -0.775169 | 0.3 |
| 7.43238 | -1.000000 | 0.3 |
已尝试以下代码,但希望找到更优实现:
sigmas, taus = centers[:,0], centers[:,1] _inputs = np.array(np.meshgrid(taus, ts)).reshape(2,9).T inputs = np.append(np.zeros((9,1)), _inputs, 1) for input in inputs: center = centers[np.where(centers[:,1]==input[1])] input[0:2] = center
优化实现方案
可以利用numpy的广播机制和repeat、tile函数高效实现,避免循环和不必要的查找操作,代码更简洁高效:
import numpy as np centers = np.array([(2.78568, 0.0000), (4.32842, -0.775169), (7.43238, -1.000000)]) ts = np.array([0.1, 0.2, 0.3]) # 重复centers,每个center对应ts中的每个元素 centers_repeated = np.repeat(centers, len(ts), axis=0) # 将ts中的每个元素重复len(centers)次,与上面的结果匹配 ts_tiled = np.tile(ts, len(centers)) # 拼接成最终的结果数组 result = np.column_stack((centers_repeated, ts_tiled)) print(result)
代码解释
np.repeat(centers, len(ts), axis=0):将centers中的每一行重复len(ts)次,得到(9,2)的数组,对应每个center依次和所有t值配对的前两列。np.tile(ts, len(centers)):将ts数组整体重复len(centers)次,得到(9,)的一维数组,对应每一组center重复完后,依次填充所有t值。np.column_stack:将两个数组按列拼接,得到预期的(9,3)结果数组。
也可以用meshgrid结合转置实现,核心是保持center的配对关系:
# 用meshgrid生成索引,保持center的配对 grid_centers, grid_ts = np.meshgrid(centers, ts, indexing='ij') # 拼接并调整形状 result = np.concatenate([grid_centers.reshape(-1,2), grid_ts.reshape(-1,1)], axis=1)
这里indexing='ij'确保meshgrid的第一个维度对应center的索引,第二个维度对应t的索引,grid_centers形状为(3,3,2),reshape后就能得到所有center和t的组合,且保持配对。
内容的提问来源于stack exchange,提问作者Shruti
相关产品推荐
相关产品推荐

