2014-12-02 37 views
0

我在熊貓中有一個數據框,第一列命名爲x0,第二列命名爲x1。它有很多(如100)行。因此,我有100組[x0,x1],然後我想要生成一個與每個組相關的長表達式。更明確地說,我想要做的任務是產生一個表達:這裏我如何使用sympy添加索引表達式

exp(b0*x00+b1*x10)+exp(b0*x01+b1*x11)+...exp(b0*(x0 100) + b1*(x1 100)) 

b0b1都是未知值(符號)和稍後我會找到自己的解決方案。

簡而言之,我需要表達sigma(exp(b0*x0+b1*x1)),sigma有100個項目,x0,x1 n是一個數據框,但我不知道如何編程循環。

請幫幫我。

回答

0

我希望這可以幫助,我不熟悉熊貓,但你需要sympy的summation(f,(i,a,b))。在本例中,你只需要聲明expr = summation(exp,(i,0,101)) 之類的東西,你的'exp'函數已經在其中包含了符號b0和b1項。

當你想打印出來時,你只需要使用pprint(expr)而不是print()。

0

一個簡單的Python for循環就足夠了以產生表達式:

>>> import numpy as np # pandas uses numpy arrays 
>>> import sympy as sym 
>>> x = np.random.rand(5,2).view(dtype=[('x0', np.float), ('x1', np.float)]) 
>>> b0, b1 = sym.symbols('b0 b1') 
>>> x['x0'] # to show the contents 
array([[ 0.1389724 ], 
     [ 0.14091647], 
     [ 0.08886302], 
     [ 0.48792306], 
     [ 0.749205 ]]) 
>>> expr = 0 
>>> for x0, x1 in zip(x['x0'], x['x1']): 
...  # build up the expression term by term: 
...  expr += sym.exp(b0 * float(x0) + b1 *float(x1)) 
... 
>>> expr 
exp(0.0888630154325879*b0 + 0.597823474111901*b1) + exp(0.138972400914926*b0 + 0.0275642343608167*b1) + exp(0.140916465250792*b0 + 0.0662746588259522*b1) + exp(0.487923064546991*b0 + 0.922545565808876*b1) + exp(0.7492050039088*b0 + 0.911117507753871*b1)