英文:
Numpy: multiply slices of final dimension by another array
问题
我有一个维度为(N, M)
的数组x
和一个维度为(N, M, 2)
的数组y
。对于任何i, j
,我想将y[i, j, :]
的每个元素乘以x[i, j]
。我应该如何做到这一点?
import numpy as np
x = np.random.randn(100, 10)
y = np.random.randn(100, 10, 2)
x * y # 这不起作用
英文:
I have an array x
of dimension (N, M)
and an array y
of dimension (N, M, 2)
. For any i, j
I would like to multiply each y[i, j, :]
by x[i, j]
. How can I do this?
import numpy as np
x = np.random.randn(100, 10)
y = np.random.randn(100, 10, 2)
x * y # this does not work
答案1
得分: 1
Add extra dim as follows:
import numpy as np
x = np.random.randn(100, 10)
print(x[..., None].shape)
y = np.random.randn(100, 10, 2)
x[..., None] * y
英文:
Add extra dim as follows:
import numpy as np
x = np.random.randn(100, 10)
print(x[..., None].shape)
y = np.random.randn(100, 10, 2)
x[..., None] * y
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论