numpy 从二维数组中减去/添加一维数组 [英] numpy subtract/add 1d array from 2d array
本文介绍了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-loops 或类似方法做一个解决方法,但应该有一个直接的方法.谢谢
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
推荐答案
需要将数组b转成(2, 1)形
数组,使用None或numpy.newaxis
在索引元组中.这是Numpy 数组的索引.
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.
你可以这样做:
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]])
这篇关于numpy 从二维数组中减去/添加一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文