问题描述
我在numpy中有两个数组A和B. A 保存笛卡尔坐标,每行是3D空间中的一个点,形状为(r,3). B 的形状为(r,n),并保存整数.
I have two arrays A and B in numpy. A holds cartesian coordinates, each row is one point in 3D space and has the shape (r, 3). B has the shape (r, n) and holds integers.
我想做的是将B的每个元素与A中的每一行相乘,以使结果数组的形状为(r,n,3).例如:
What I would like to do is multiply each element of B with each row in A, so that the resulting array has the shape (r, n, 3). So for example:
# r = 3
A = np.array([1,1,1, 2,2,2, 3,3,3]).reshape(3,3)
# n = 2
B = np.array([10, 20, 30, 40, 50, 60]).reshape(3,2)
# Result with shape (3, 2, 3):
# [[[10,10,10], [20,20,20]],
# [[60,60,60], [80,80,80]]
# [[150,150,150], [180,180,180]]]
我非常确定可以使用 ,但我已经尝试了很长一段时间,无法正常工作.
I'm pretty sure this can be done with np.einsum
, but I've been trying this for quite a while now and can't get it to work.
推荐答案
使用 broadcasting
-
A[:,None,:]*B[:,:,None]
由于 np.einsum
也支持广播,您也可以使用它(感谢@ajcr建议这个简洁的版本)-
Since np.einsum
also supports broadcasting, you can use that as well (thanks to @ajcr for suggesting this concise version) -
np.einsum('ij,ik->ikj',A,B)
样品运行-
In [22]: A
Out[22]:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
In [23]: B
Out[23]:
array([[10, 20],
[30, 40],
[50, 60]])
In [24]: A[:,None,:]*B[:,:,None]
Out[24]:
array([[[ 10, 10, 10],
[ 20, 20, 20]],
[[ 60, 60, 60],
[ 80, 80, 80]],
[[150, 150, 150],
[180, 180, 180]]])
In [25]: np.einsum('ijk,ij->ijk',A[:,None,:],B)
Out[25]:
array([[[ 10, 10, 10],
[ 20, 20, 20]],
[[ 60, 60, 60],
[ 80, 80, 80]],
[[150, 150, 150],
[180, 180, 180]]])
这篇关于将一个数组的每一行与另一个数组的每个元素乘以numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!