numpy从2D数组中减去/添加1D数组 [英] numpy subtract/add 1d array from 2d array

查看:71
本文介绍了numpy从2D数组中减去/添加1D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2D阵列:

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 to a (2, 1) shape数组,在索引元组中使用None or numpy.newaxis.这是为Numpy数组建立索引. /p>

您可以这样做:

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]])

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. Thanks

解决方案

You need to convert array b to a (2, 1) shape array, use None or numpy.newaxis in the index tuple. Here is the Indexing of Numpy array.

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]])

这篇关于numpy从2D数组中减去/添加1D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆