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

标签 python arrays math numpy

在 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/

相关文章:

python - genfromtxt 返回 -1 和 nan 行

ios - 如何从任意数组中的枚举获取原始值

C:根据给定条件查找序列的成员

java - 查看管道技术示例

python - 在 PySpark 日期列中获取每年的最新日期

python - 在 Python 中使用 URL 查询字符串构建请求

php - 如何防止在我的服务器上上传每一个恶意文件? (检查文件类型)?

php - 在用[]添加值之前是否需要声明PHP数组?

c - 初始化指向整数数组的指针。

c - 模乘法(C 语言)