[英]Python output to csv file
I have a question in output to a csv file in Python: 我在输出到Python中的csv文件时有一个问题:
Code as below: 代码如下:
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())
This part of code works fine for me and I got Qstar = 5 in this simple example. 这部分代码对我来说很好用,在这个简单的示例中我得到了Qstar = 5。 How could I output it to a csv file?
如何将其输出到csv文件?
I have the following code to call Qstar: 我有以下代码调用Qstar:
with open('test.csv', 'wb') as fp:
a = csv.writer(fp, delimiter=',')
data = [['Order_Number'],['Qstar']]
a.writerows(data)
But it seems I only obtain 但似乎我只能得到
The nhow could I call 'Qstar' correctly? 我怎么能正确地称呼“ Qstar”?
Thank you! 谢谢!
By using single quotes around Qstar you are telling Python to create a string with the value 'Qstar'. 通过在Qstar周围使用单引号,您将告诉Python创建一个值为'Qstar'的字符串。 In order to output the value of the variable Qstar, just don't use the single quotes:
为了输出变量Qstar的值,只需不要使用单引号:
with open('test.csv', 'wb') as fp:
a = csv.writer(fp, delimiter=',')
data = [['Order_Number'],[Qstar]]
a.writerows(data)
That's because you feed data array with strings instead of numbers. 那是因为您用字符串而不是数字来喂数据数组。 Remove the single quotes from Qstar and Order_number.
从Qstar和Order_number中删除单引号。
Try this: 尝试这个:
with open('test.csv', 'wb') as fp:
a = csv.writer(fp, delimiter=',')
data = [['Order_Number'],[Qstar]]
a.writerows(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.