[英]numpy subtract/add 1d array from 2d array
I have the following 2D-array:我有以下二维数组:
a = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
and another 1D-array:和另一个一维数组:
b = array([ 1, 2, 3, 4, 5])
then I want to calculate something like然后我想计算类似的东西
c = a - b
with the intent of getting:旨在获得:
c = array([[0, 1, 2],
[2, 3, 4],
[4, 5, 6],
[6, 7, 8],
[8, 9, 10]])
but instead I get the error message:但我收到了错误消息:
Traceback (most recent call last):
Python Shell, prompt 79, line 1
ValueError: operands could not be broadcast together with shapes (5,3) (5,)
I read the broadcasting rules but didn´t get any wiser.我阅读了广播规则,但没有变得更明智。 I could do a workaround with for-loops or similar but there should be a direct way.
我可以用 for-loops 或类似方法做一个解决方法,但应该有一个直接的方法。 Thanks
谢谢
You need to convert array b to a (2, 1) shape
array, use None or numpy.newaxis
in the index tuple. 您需要将数组
b to a (2, 1) shape
转换b to a (2, 1) shape
数组,在索引元组中使用None or numpy.newaxis
。 Here is the Indexing of Numpy array . 这是Numpy数组的索引 。
You can do it Like: 你可以这样做:
import numpy
a = numpy.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
b = numpy.array([ 1, 2, 3, 4, 5])
c=a - b[:,None]
print c
Output: 输出:
Out[2]:
array([[ 0, 1, 2],
[ 2, 3, 4],
[ 4, 5, 6],
[ 6, 7, 8],
[ 8, 9, 10]])
As Divakar specified in the comments, just add a new axis to b
. 正如评论中指定的Divakar,只需向
b
添加一个新轴。
I suggest you read more about broadcasting which is very often useful to vectorize computations in numpy: interestingly enough, a.transpose() - b
wouldn't have raised an error (you'd need to transpose the result again to obtain your desired output). 我建议你阅读更多有关广播的内容 ,这对于在numpy中矢量化计算非常有用:有趣的是,
a.transpose() - b
不会引发错误(你需要再次转置结果以获得所需的输出)。
In this computaion, the first array's shape is (3, 5)
, and b.shape
is (5,). 在这个计算中,第一个数组的形状是
(3, 5)
,而b.shape
是(5,)。 So the shape of b
corresponds to the tail of the shape of a
, and broadcasting can happen. 所以形状
b
对应的形状的尾巴a
,和广播可能发生。 This is not the case when the shape of the first array is (5, 3)
, hence the error you obtained. 当第一个数组的形状为
(5, 3)
,情况并非如此,因此您获得的错误。
Here are some runtime tests to compare the speeds of the suggested answers, with your values for a
and b
: you can see that the differences are not really significant 以下是一些运行时测试,用于比较建议答案的速度,以及
a
和b
值:您可以看到差异不是很显着
In [9]: %timeit (a.T - b).T
Out[9]: 1000000 loops, best of 3: 1.32 µs per loop
In [10]: %timeit a - b[:,None]
Out[10]: 1000000 loops, best of 3: 1.25 µs per loop
In [11]: %timeit a - b[None].T
Out[11]: 1000000 loops, best of 3: 1.3 µs per loop
Sometimes is usefull to do this: 有时这样做很有用:
C = numpy.zeros(shape=A.shape)
for i in range(len(A)):
C[i] = A[i] - B[i]
S = C.astype(int)
print(S)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.