2017-04-06 89 views
0

我在輸出問題Python中的CSV文件:Python的輸出到CSV文件

代碼如下:

 import numpy as np 
    import scipy.stats as stats 
    from scipy.stats import poisson, norm 

    # Read the csv file and obtain corresponding parameter mu, cs and co. 

    import csv 
    with open('r1.csv', 'r') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     print row 
    mu = row[0] 
    cs = row[1] 
    co = row[2] 

    mu = float(mu) 
    cs = float(cs) 
    co = float(co) 

    # Generate a Poisson Distribution and 

    G = poisson(mu) 
    p = G.pmf(np.arange(3*mu)) 

    # Define Z(Q) for the total cost estimation 

    def Z(Q): 
     ES = sum(i*p[i] for i in range(len(p))) 
     return cs*max((Q-ES), 0) + co*max((ES-Q), 0) 

    # Obtain Qstar 

    Qstar = np.ceil(poisson.ppf(co/(cs+co), mu))-1 
    Qstar = int(np.float64(Qstar).item()) 

這部分代碼工作正常,我和我QSTAR = 5在這個簡單的例子。我怎樣才能把它輸出到一個CSV文件?

ORDER_NUMBER

我有以下的代碼來調用QSTAR:

with open('test.csv', 'wb') as fp: 
     a = csv.writer(fp, delimiter=',') 
     data = [['Order_Number'],['Qstar']] 
     a.writerows(data) 

但似乎我只獲得

ORDER_NUMBER

QSTAR

我可以正確地稱'Qstar'嗎?

謝謝!

+0

從各地QSTAR採取引號下來,你會得到QSTAR舉行的變量。 –

+0

謝謝! @MohammadAthar – Chenxi

回答

0

試試這個:

with open('test.csv', 'wb') as fp: 
      a = csv.writer(fp, delimiter=',') 
      data = [['Order_Number'],[Qstar]] 
      a.writerows(data) 
0

通過在Qstar周圍使用單引號,您告訴Python創建一個值爲'Qstar'的字符串。爲了輸出變量QSTAR的價值,只是不使用單引號:

with open('test.csv', 'wb') as fp: 
    a = csv.writer(fp, delimiter=',') 
    data = [['Order_Number'],[Qstar]] 
    a.writerows(data) 
+0

謝謝!就是這樣@ldueck – Chenxi

0

那是因爲你給的數據陣列字符串,而不是數字。從Qstar和Order_number刪除單引號。

+0

非常感謝! @Sahin – Chenxi