在python中,我希望从1维数组中逐行减去2维数组。
我知道如何使用“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]
这是一个不起作用的示例,将“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
您有什么建议吗?