Python输出到csv文件

时间:2017-04-06 14:53:11

标签: python csv output

我在输出到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

5

我有以下代码来调用Qstar:

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

但似乎我只获得了

ORDER_NUMBER

QSTAR

nhow我可以正确地称'Qstar'吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

通过在Qstar周围使用单引号,您告诉Python创建一个值为'Qstar'的字符串。为了输出变量Qstar的值,只需不要使用单引号:

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

答案 1 :(得分:0)

那是因为您使用字符串而不是数字来提供数据数组。从Qstar和Order_number中删除单引号。

答案 2 :(得分:0)

试试这个:

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