leo*_*lds 16 python arrays numpy
我有以下2D数组:
a = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
Run Code Online (Sandbox Code Playgroud)
和另一个1D阵列:
b = array([ 1, 2, 3, 4, 5])
Run Code Online (Sandbox Code Playgroud)
然后我想计算类似的东西
c = a - b
Run Code Online (Sandbox Code Playgroud)
旨在获得:
c = array([[0, 1, 2],
[2, 3, 4],
[4, 5, 6],
[6, 7, 8],
[8, 9, 10]])
Run Code Online (Sandbox Code Playgroud)
但我得到错误信息:
Traceback (most recent call last):
Python Shell, prompt 79, line 1
ValueError: operands could not be broadcast together with shapes (5,3) (5,)
Run Code Online (Sandbox Code Playgroud)
我阅读了广播规则,但没有更明智.我可以使用for循环或类似方法进行解决,但应该有一个直接的方法.谢谢
Sak*_*med 24
你需要转换数组b to a (2, 1) shape数组,None or numpy.newaxis在索引元组中使用.这是Numpy数组的索引.
你可以这样做:
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
Run Code Online (Sandbox Code Playgroud)
输出:
Out[2]:
array([[ 0, 1, 2],
[ 2, 3, 4],
[ 4, 5, 6],
[ 6, 7, 8],
[ 8, 9, 10]])
Run Code Online (Sandbox Code Playgroud)