python每行输入一个数组_Python和numpy的:减去一行行从1维数组一个2维数组

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 "", line 1, in

ValueError: shape mismatch: objects cannot be broadcast to a single shape

Dou you have suggestions ?

解决方案

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]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值