Python 如何将一个向量的每个元素提升为另一个向量的每个元素的幂?
我想通过从0到5的升幂来提升一个向量:Python 如何将一个向量的每个元素提升为另一个向量的每个元素的幂?,python,numpy,array-broadcasting,Python,Numpy,Array Broadcasting,我想通过从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 co
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,)
这里有一个解决方案:
num_of_powers = 5
num_of_components = 11
a = []
for i in range(1,num_of_components + 1):
a.append(np.repeat(i,num_of_powers))
b = list(range(num_of_powers))
c = np.power(a,b)
输出c
如下所示:
array([[ 1, 1, 1, 1, 1],
[ 1, 2, 4, 8, 16],
[ 1, 3, 9, 27, 81],
[ 1, 4, 16, 64, 256],
[ 1, 5, 25, 125, 625],
[ 1, 6, 36, 216, 1296],
[ 1, 7, 49, 343, 2401],
[ 1, 8, 64, 512, 4096],
[ 1, 9, 81, 729, 6561],
[ 1, 10, 100, 1000, 10000],
[ 1, 11, 121, 1331, 14641]], dtype=int32)
您的解决方案显示广播错误,因为根据:
如果x1.shape!=x2.shape,它们必须可以广播到公共形状(成为输出的形状)
c=[[x**y代表b中的y]代表a中的x]
首先需要创建一个矩阵,其中的行是每个数字的重复。这可以通过以下方式实现:
然后将其提升到b
elementwise的幂次方:
np.power(mat, b)
总而言之:
将numpy导入为np
nums=np.数组([1,2,3])#11个组件的列表
幂=np.数组([0,1,2,3,4])#幂
打印(np.power(np.tile(nums,(len(powers),1)).transpose(),powers))
这将提供:
[[ 1 1 1 1 1] # == [1**0, 1**1, 1**2, 1**3, 1**4]
[ 1 2 4 8 16] # == [2**0, 2**1, 2**2, 2**3, 2**4]
[ 1 3 9 27 81]] # == [3**0, 3**1, 3**2, 3**3, 3**4]
一种解决方案是向数组
a
c = a[:,None]**b
# Using broadcasting :
# (3,1)**(4,) --> (3,4)
#
# [[1],
# c = [2], ** [0,1,2,3,4]
# [3]]
有关更多信息,请查看numpy
.tolist()
不必要的编辑在这一条上很强哈哈:[[x**y代表y in b]代表x in a]
就足够了:)c=[[x**y代表y in b]代表x in a]
你的力量总是这样增长吗?听起来你想要一个Vandermone矩阵。我正在寻找一个Vandermone矩阵。它确实是最好/最快的解决方案!太神了我对numpy不是很熟练,我正在寻找一种复制元素的方法,但这甚至不是必需的!多谢各位much@Hamza如果答案对你有效,你可以接受它(投票部分下方的勾号),以确认它是解决方案。
[[ 1 1 1 1 1] # == [1**0, 1**1, 1**2, 1**3, 1**4]
[ 1 2 4 8 16] # == [2**0, 2**1, 2**2, 2**3, 2**4]
[ 1 3 9 27 81]] # == [3**0, 3**1, 3**2, 3**3, 3**4]
c = a[:,None]**b
# Using broadcasting :
# (3,1)**(4,) --> (3,4)
#
# [[1],
# c = [2], ** [0,1,2,3,4]
# [3]]