如何通过标量数组乘以numpy元组数组

Sti*_*fel 3 python arrays tuples numpy

我有一个形状(N,2)的numpy数组A和形状(N)的numpy数组S.

如何将两个数组相乘?目前我正在使用此代码:

tupleS = numpy.zeros( (N , 2) )
tupleS[:,0] = S
tupleS[:,1] = S
product = A * tupleS
Run Code Online (Sandbox Code Playgroud)

我是一个蟒蛇初学者.有一个更好的方法吗?

sen*_*rle 6

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]])
Run Code Online (Sandbox Code Playgroud)