I have an example csv file with name 'r2.csv'
:
Factory | Product_Number | Date | Avg_Noshow | Walk_Cost | Room_Rev
-------------------------------------------------------------------------
A | 1 | 01APR2017 | 5.6 | 125 | 275
-------------------------------------------------------------------------
A | 1 | 02APR2017 | 4.5 | 200 | 300
-------------------------------------------------------------------------
A | 1 | 03APR2017 | 6.6 | 150 | 250
-------------------------------------------------------------------------
A | 1 | 04APR2017 | 7.5 | 175 | 325
-------------------------------------------------------------------------
I have the following python code to read a csv file and transfer the columns to arrays:
# Read csv file
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 computation.
mu = data['Avg_Noshow']
cs = data['Walk_Cost']
co = data['Room_Rev']
mu = map(float,mu)
cs = map(float,cs)
co = map(float,co)
It runs fine except for the last row and has the following error message:
File "<stdin>", line 1, in <module>
KeyError: 'Room_Rev'
How could I avoid it?