Python和numpy的:减去一行行从1维数组一个2维数组 [英] Python and numpy : subtracting line by line a 2-dim array from a 1-dim array

查看:1153
本文介绍了Python和numpy的:减去一行行从1维数组一个2维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我想从1维数组减去一行行的2维数组。

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

我知道如何与一个for循环和索引的做到这一点,但我想这可能会更快使用numpy的功能。但是我没有找到一个方法来做到这一点。这是一个带'for'循环的例子:

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]

这是一些不工作的范例,通过这种取代'for'循环:

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 ?

推荐答案

的问题是, YX 有各自的形状(2)(2 5)。要做到正确的广播,你需要的形状(2,1)(2,5)。我们可以用 .reshape 做到这一点,只要元素的数量是preserved:

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

给出:

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

这篇关于Python和numpy的:减去一行行从1维数组一个2维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆