在 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]
这里是一个不起作用的例子,用这个代替'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
你有什么建议吗?
最佳答案
问题在于 y-x
具有各自的形状 (2) (2,5)
。要进行适当的广播,您需要形状 (2,1) (2,5)
。只要保留元素的数量,我们就可以使用 .reshape
来做到这一点:
y.reshape(2,1) - x
给予:
array([[19, 18, 17, 16, 15],
[ 4, 3, 2, 1, 0]])
关于Python 和 numpy : subtracting line by line a 2-dim array from a 1-dim array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10178823/