[英]How to multiply numpy 1D with N-D array?
我有一個 numpy 陣列 A:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
而另一個數組B:
array([0, 1])
如何將 A 和 B 相乘得到結果?
array([[[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
非常感謝。
您需要重塑第二個 ndarray 以便 arrays 具有相同的維度數:
arr1 * arr2[:, None, None]
或者
arr1 * arr2.reshape(2, 1, -1)
arr1.shape
# (2, 3, 4)
arr2[:, None, None].shape
# (2, 1, 1)
arr2.reshape(2, 1, -1).shape
# (2, 1, 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.