2014-11-02 24 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]) 
相關問題