逐行插入2D Numpy数组的值 [英] Interpolate values row-wise for 2D Numpy array
本文介绍了逐行插入2D Numpy数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个numpy数组:
I have two numpy arrays:
x = np.array([1,2,3,4,5])
y = np.array([10,20,30,40,50])
我试图得到的是这样的:
What I try to get is something like this:
array([[ 1. , 3.25, 5.5 , 7.75, 10. ],
[ 2. , 6.5 , 11. , 15.5 , 20. ],
[ 3. , 9.75, 16.5 , 23.25, 30. ],
[ 4. , 13. , 22. , 31. , 40. ],
[ 5. , 16.25, 27.5 , 38.75, 50. ]])
我的方法不是很像Numpy,需要对非常大的数组进行改进(摆脱for循环):
My approach is not very Numpy like and needs improvement (getting rid of the for-loop) for very large arrays:
myarray = np.zeros((5,5))
for idx in np.arange(5):
myarray[idx,:] = np.linspace(x[idx], y[idx], 5)
在Numpy中执行此操作的最佳方法是什么? 这样生成myarray然后对其进行操作会更好吗?
What would be a good approach to do this in Numpy? Would it be better to generate the myarray this way and then manipulate it?
myarray = np.zeros((5,5))
myarray[:,0] = x
myarray[:,-1] = y
array([[ 1., 0., 0., 0., 10.],
[ 2., 0., 0., 0., 20.],
[ 3., 0., 0., 0., 30.],
[ 4., 0., 0., 0., 40.],
[ 5., 0., 0., 0., 50.]])
推荐答案
此广播技巧有效:
>>> x = np.array([1,2,3,4,5])
>>> y = np.array([10,20,30,40,50])
>>> z = np.linspace(0, 1, 5)
>>> z[None, ...] * (y[..., None] - x[..., None]) + ( x[..., None])
array([[ 1. , 3.25, 5.5 , 7.75, 10. ],
[ 2. , 6.5 , 11. , 15.5 , 20. ],
[ 3. , 9.75, 16.5 , 23.25, 30. ],
[ 4. , 13. , 22. , 31. , 40. ],
[ 5. , 16.25, 27.5 , 38.75, 50. ]])
>>>
这篇关于逐行插入2D Numpy数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文