将数组的值添加到numpy矩阵

时间:2015-08-24 21:36:35

标签: python arrays numpy matrix sum

我想将numpy数组中的值添加到numpy矩阵的特定行中的值。

假设:

A = [[0, 0], [0, 0]]

b = [1, 1]

我想将b添加到A中第一行的值。预期输出为:

[[1, 1], [0, 0]]

我尝试使用“+”运算符,但收到错误:

>>> import numpy
>>> a = numpy.zeros(shape=(2,2))
>>> a
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> b = numpy.ones(shape=(1,2))
>>> b
array([[ 1.,  1.]])

>>> a[0, :] += b

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: non-broadcastable output operand with shape (2,) doesn't match the broadcast shape (1,2)

这样做的最佳方式是什么?

0 个答案:

没有答案