我想通过从 0 到 5 的递增幂来提高向量:
import numpy as np
a = np.array([1, 2, 3]) # list of 11 components
b = np.array([0, 1, 2, 3, 4]) # power
c = np.power(a,b)
期望的结果是:c = [[1**0, 1**1, 1**2, 1**3, 1**4], [2**0, 2**1, ...], ...]
我不断收到此错误:ValueError: operands could not be broadcast together with shapes (3,) (5,)
最佳答案
一种解决方案是为数组添加一个新维度 a
c = a[:,None]**b
# Using broadcasting :
# (3,1)**(4,) --> (3,4)
#
# [[1],
# c = [2], ** [0,1,2,3,4]
# [3]]
有关更多信息,请查看 numpy broadcasting documentation
关于python - 如何将向量的每个元素提升为另一个向量的每个元素的幂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66242475/