简体   繁体   中英

Python output to csv file

I have a question in output to a csv file in Python:

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. How could I output it to a csv file?

Order_Number

5

I have the following code to call 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

Order_Number

Qstar

The nhow could I call 'Qstar' correctly?

Thank you!

By using single quotes around Qstar you are telling Python to create a string with the value 'Qstar'. In order to output the value of the variable Qstar, just don't use the single quotes:

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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM