lundi 1 mai 2017

How to add 'if' when defining function and doing calculation using Python

I have an example csv file with name 'r2.csv':

Factory | Product_Number |   Date     | Avg_Noshow | Walk_Cost | Room_Rev
-------------------------------------------------------------------------
   A    |      1         | 01MAY2017  |   5.6      |  125      |  275
-------------------------------------------------------------------------
   A    |      1         | 02MAY2017  |   0        |  200      |  300
-------------------------------------------------------------------------
   A    |      1         | 03MAY2017  |   6.6      |  150      |  250
-------------------------------------------------------------------------
   A    |      1         | 04MAY2017  |   7.5      |  175      |  325
-------------------------------------------------------------------------

And I would like to read the file and calculate as output using the following code:

I have the following python code to read a csv file and transfer the columns to arrays:

# Read csv file
import numpy as np
import scipy.stats as stats
from scipy.stats import poisson, norm
import csv

with open('r2.csv', 'r') as infile:

   reader = csv.DictReader(infile)
   data = {}
   for row in reader:
       for header, value in row.items():
          try:
                data[header].append(value)
          except KeyError:
                data[header] = [value]

 # Transfer the column from list to arrays for later calculation.

mu = data['Avg_Noshow']
cs = data['Walk_Cost']
co = data['Room_Rev']

mu = map(float,mu)
cs = map(float,cs)
co = map(float,co)

The prior part works fine and it reads data. Following is the function for calculation.

# The following calculates Overbooking number 
Overbooking_Number = map(lambda mu_,cs_,co_:np.ceil(poisson.ppf(co_/(cs_+co_),mu_)),mu,cs,co)

data['Overbooking_Number'] = Overbooking_Number
header = 'LOC_ID', 'Prod_Class_ID', 'Date', 'Avg_Noshow', 'Walk_Cost', 'Room_Rev', 'Overbooking_Number'

# Write to an output file 
with open("output.csv",'wb') as resultFile:
    wr = csv.writer(resultFile,quoting=csv.QUOTE_ALL)
    wr.writerow(header)
    z = zip(data['LOC_ID'],data['Prod_Class_ID'],data['Date'],data['Avg_Noshow'],data['Walk_Cost'],data['Room_Rev'],data['Overbooking_Number'])
       for i in z:
          wr.writerow(i)

It works fine as well.

However, if I would like to calculate and output 'Overbooking_Number' using the above function only if 'Avg_Noshow > 0' and output 'Overbooking_Number = 0' if 'Avg_Noshow = 0'?

What shall I add to the second part of the code?

Thank you!

Aucun commentaire:

Enregistrer un commentaire