我有两个numpy数组:
x = np.array([1,2,3,4,5])
y = np.array([10,20,30,40,50])
我试图得到的是这样的:
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循环):
myarray = np.zeros((5,5))
for idx in np.arange(5):
myarray[idx,:] = np.linspace(x[idx], y[idx], 5)
在Numpy中这样做的好方法是什么? 以这种方式生成myarray然后操纵它会更好吗?
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.]])
答案 0 :(得分:4)
这种广播技巧有效:
>>> 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. ]])
>>>
答案 1 :(得分:1)
这是使用np.nditer
迭代数组的另一种解决方案:
>>> import numpy as np
>>> n = 5
>>> x = np.array([1,2,3,4,5])
>>> y = np.array([10,20,30,40,50])
>>> z = np.empty(shape=(n, x.shape[0]), dtype=float)
>>> for k, (i,j) in enumerate(np.nditer([x,y])):
z[k,:] = np.linspace(i,j,n)
>>> z
[[ 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. ]]