我有以下变量:
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 网格化。即,我想要以下输出:
西格玛 | 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
我尝试了网格网格的几种参数组合,但没有达到我想要的效果。有人可以帮忙吗?
有多种方法。
一种是使用repeat/tile来扩展两个数组,然后将它们连接起来。
另一种方法是从正确大小的零数组开始(3d 最简单),利用广播的优势,沿着正确的维度组合分配值。
In [22]: res = np.zeros((centers.shape[0], ts.shape[0], centers.shape[1]+1))
In [23]: res[:,:,:-1]=centers[None,:,:] # (1,3,2)
In [24]: res[:,:,-1] = ts[:,None] # (3,1)
In [25]: res
Out[25]:
array([[[ 2.78568 , 0. , 0.1 ],
[ 4.32842 , -0.775169, 0.1 ],
[ 7.43238 , -1. , 0.1 ]],
[[ 2.78568 , 0. , 0.2 ],
[ 4.32842 , -0.775169, 0.2 ],
[ 7.43238 , -1. , 0.2 ]],
[[ 2.78568 , 0. , 0.3 ],
[ 4.32842 , -0.775169, 0.3 ],
[ 7.43238 , -1. , 0.3 ]]])
然后重塑以获得您想要的 2d:
In [26]: res.reshape(-1,3)
Out[26]:
array([[ 2.78568 , 0. , 0.1 ],
[ 4.32842 , -0.775169, 0.1 ],
[ 7.43238 , -1. , 0.1 ],
[ 2.78568 , 0. , 0.2 ],
[ 4.32842 , -0.775169, 0.2 ],
[ 7.43238 , -1. , 0.2 ],
[ 2.78568 , 0. , 0.3 ],
[ 4.32842 , -0.775169, 0.3 ],
[ 7.43238 , -1. , 0.3 ]])