Python 将数组提升为不同的值
我正计划为不同的n值绘制y^n vs x。以下是我的示例代码:Python 将数组提升为不同的值,python,Python,我正计划为不同的n值绘制y^n vs x。以下是我的示例代码: import numpy as np x=np.range(1,5) y=np.range(2,9,2) exponent=np.linspace(1,8,50) z=y**exponent 这样,我得到了以下错误: ValueError: operands could not be broadcast together with shapes (4) (5) 我的想法是,对于n的每个值,我将得到一个数组,其中该数组包含
import numpy as np
x=np.range(1,5)
y=np.range(2,9,2)
exponent=np.linspace(1,8,50)
z=y**exponent
这样,我得到了以下错误:
ValueError: operands could not be broadcast together with shapes (4) (5)
我的想法是,对于n的每个值,我将得到一个数组,其中该数组包含y的新值,该值现在提升为n。例如:
y1= [] #an array where y**1
y2= [] #an array where y**1.5
y3= [] #an array where y**2
等等。我不知道如何才能为y**n获得50个阵列,有没有更简单的方法?谢谢。您可以使用文档中介绍的广播并创建一个新轴:
z = y**exponent[:,np.newaxis]
换句话说,不是
>>> y = np.arange(2,9,2)
>>> exponent = np.linspace(1, 8, 50)
>>> z = y**exponent
Traceback (most recent call last):
File "<ipython-input-40-2fe7ff9626ed>", line 1, in <module>
z = y**exponent
ValueError: operands could not be broadcast together with shapes (4,) (50,)
诸如此类
>>> z = y**exponent[:,np.newaxis]
>>> z.shape
(50, 4)
>>> z[0]
array([ 2., 4., 6., 8.])
>>> z[1]
array([ 2.20817903, 4.87605462, 7.75025005, 10.76720154])
>>> z[0]**exponent[1]
array([ 2.20817903, 4.87605462, 7.75025005, 10.76720154])
>>> z = y**exponent[:,np.newaxis]
>>> z.shape
(50, 4)
>>> z[0]
array([ 2., 4., 6., 8.])
>>> z[1]
array([ 2.20817903, 4.87605462, 7.75025005, 10.76720154])
>>> z[0]**exponent[1]
array([ 2.20817903, 4.87605462, 7.75025005, 10.76720154])