python - numpy 从二维数组中减去/添加一维数组

标签 python arrays numpy

我有以下二维数组:

a = array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [10, 11, 12],
           [13, 14, 15]])

和另一个一维数组:

b = array([ 1,  2,  3,  4,  5])

然后我想计算类似的东西

c = a - b

为了得到:

c = array([[0, 1,  2],
           [2, 3,  4],
           [4, 5,  6],
           [6, 7,  8],
           [8, 9, 10]])

但我收到错误消息:

Traceback (most recent call last):
  Python Shell, prompt 79, line 1
ValueError: operands could not be broadcast together with shapes (5,3) (5,)

我阅读了广播规则,但并没有变得更聪明。我可以使用 for 循环或类似方法来解决问题,但应该有直接的方法。谢谢

最佳答案

您需要将数组 b 转换为 (2, 1) 形状 数组,在索引元组中使用 None 或 numpy.newaxis。这是 Indexing of Numpy array .

你可以这样做:

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

输出:

Out[2]: 
array([[ 0,  1,  2],
       [ 2,  3,  4],
       [ 4,  5,  6],
       [ 6,  7,  8],
       [ 8,  9, 10]])

关于python - numpy 从二维数组中减去/添加一维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33303348/

相关文章:

java - 如何从这两个数组生成一组指定数量的数字?

Python,numpy 排序数组

python - 如何在电影评级推荐系统中应用归一化平均绝对值来提高模型准确性::

python - 使用 selenium get_attribute 扭曲 HTML 内容

Python - 使用 Setuptools 打包 Alembic 迁移

javascript - 带推送的递归数组

javascript - 如何在满足特定条件的情况下随机化数组?

NumPy 与 Theano?

python - 如何使用 easy_install 安装 Pandas ?

python - 如果将数组乘以等于或大于 10**20 的数字,为什么 numpy 数组的 dtype 会自动更改为 'object'?