Python and numpy : subtracting line by line a 2-dim array from a 1-dim array

杀马特。学长 韩版系。学妹 提交于 2020-01-24 05:37:45

问题


In python, I wish to subtract line by line a 2-dim array from a 1-dim array.

I know how to do it with a 'for' loop and indexes but I suppose it may be quicker to use numpy functions. However I did not find a way to do it. Here is an example with a 'for' loop :

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]

And here is an example of something that does not work, replacing the 'for' loop by this:

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

Dou you have suggestions ?


回答1:


The problem is that y-x have the respective shapes (2) (2,5). To do proper broadcasting, you'll need shapes (2,1) (2,5). We can do this with .reshape as long as the number of elements are preserved:

y.reshape(2,1) - x

Gives:

array([[19, 18, 17, 16, 15],
   [ 4,  3,  2,  1,  0]])



回答2:


y[:,newaxis] - x 

should work too. The (little) comparative benefit is then you pay attention to the dimensions themselves, instead of the sizes of dimensions.



来源:https://stackoverflow.com/questions/10178823/python-and-numpy-subtracting-line-by-line-a-2-dim-array-from-a-1-dim-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!