如何用标量数组乘以numpy元组数组

3 投票
5 回答
4931 浏览
提问于 2025-04-16 20:48

我有一个形状为(N,2)的numpy数组A,还有一个形状为(N)的numpy数组S。

我该怎么把这两个数组相乘呢?现在我用的是这段代码:

tupleS = numpy.zeros( (N , 2) )
tupleS[:,0] = S
tupleS[:,1] = S
product = A * tupleS

我刚开始学python,有没有更好的方法可以做到这一点?

5 个回答

1

你试过这个吗:

product = A * S
3

基本上和@senderle的回答是一样的,但不需要直接修改S。你可以通过使用索引None来获取数组的切片,这样会增加维度:A * S[:,None]

>>> S = np.arange(5)
>>> S
array([0, 1, 2, 3, 4])
>>> A = np.arange(10).reshape((5,2))
>>> A
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
>>> S[:,None]
array([[0],
       [1],
       [2],
       [3],
       [4]])
>>> A * S[:,None]
array([[ 0,  0],
       [ 2,  3],
       [ 8, 10],
       [18, 21],
       [32, 36]])
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]])

撰写回答