2014-11-02 54 views
0

我正在计划绘制y^n vs x对于不同的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 

等。我不知道我是否可以得到这50个数组为y ** n,有没有更容易的方法来做到这一点?谢谢。

回答

0

您可以使用 “广播”(解释了文档here),并创建一个新的轴:

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,) 

可以使用array[:,np.newaxis](或array[:,None] ,同样的事情,但newaxis是更明确的关于你的意图)给阵列的尺寸1的额外维度:

>>> exponent.shape 
(50,) 
>>> exponent[:,np.newaxis].shape 
(50, 1) 

等等

>>> 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])