4

在 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

你有什么建议吗?

4

2 回答 2

7

问题是y-x有各自的形状(2) (2,5)。要进行正确的广播,您需要 shape (2,1) (2,5).reshape只要保留元素的数量,我们就可以做到这一点:

y.reshape(2,1) - x

给出:

array([[19, 18, 17, 16, 15],
   [ 4,  3,  2,  1,  0]])
于 2012-04-16T17:36:30.970 回答
2
y[:,newaxis] - x 

也应该工作。(小)比较好处是你关注维度本身,而不是维度的大小。

于 2012-06-26T15:54:51.467 回答