【问题标题】:Python and numpy : subtracting line by line a 2-dim array from a 1-dim arrayPython和numpy:从1-dim数组中逐行减去2-dim数组
【发布时间】:2012-04-16 17:32:04
【问题描述】:

在 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

你有什么建议吗?

【问题讨论】:

  • 作为建议,我会避免创建一个名为 j 的列表变量。从语法上讲,这没问题,但大多数程序员在循环中为计数器保留字母 i,j,k,这可能会导致一些混乱。

标签: python arrays math numpy


【解决方案1】:

问题是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]])

【讨论】:

    【解决方案2】:
    y[:,newaxis] - x 
    

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

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      相关资源
      最近更新 更多