gpt4 book ai didi

python - 如何将 numpy 1D 与 N 维数组相乘?

转载 作者:行者123 更新时间:2023-12-01 00:27:24 24 4
gpt4 key购买 nike

我有一个 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]]])

非常感谢。

最佳答案

您需要 reshape 第二个 ndarray,以便两个数组具有相同的维数:

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)

关于python - 如何将 numpy 1D 与 N 维数组相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58455293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com