我有一个形状(N,2)的numpy数组A和形状(N)的numpy数组S.
如何将两个数组相乘?目前我正在使用此代码:
tupleS = numpy.zeros( (N , 2) )
tupleS[:,0] = S
tupleS[:,1] = S
product = A * tupleS
我是一个Python初学者.有一个更好的方法吗?
解决方法:
Numpy使用行主要顺序,因此您必须显式创建列.如:
>> A = numpy.array(range(10)).reshape(5, 2)
>>> B = numpy.array(range(5))
>>> B
array([0, 1, 2, 3, 4])
>>> A * B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
>>> B = B.reshape(5, 1)
>>> B
array([[0],
[1],
[2],
[3],
[4]])
>>> A * B
array([[ 0, 0],
[ 2, 3],
[ 8, 10],
[18, 21],
[32, 36]])