在python中,我希望逐行从1-dim数组中减去2-dim数组.
我知道如何使用'for'循环和索引,但我想它可能更快使用numpy函数.但是我没有办法做到这一点.这是一个带有'for'循环的示例:
from numpy import *
x=array([[1,2,3,4,5],[6,7,8,9,10]])
y=array([20,10])
j=array([0, 1])
a=zeros([2,5])
for i in j :
... a[i]=y[i]-x[i]
Run Code Online (Sandbox Code Playgroud)
这里有一个不起作用的例子,用这个代替'for'循环:
a=y[j]-x[j,i]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
Run Code Online (Sandbox Code Playgroud)
你有什么建议?