Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError reading csv file and transferring to array

Tags:

python

arrays

csv

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?

like image 659
Chenxi Avatar asked Nov 08 '22 23:11

Chenxi


1 Answers

I worked off just the top two rows of your csv but this gives you the desired output:

with open('r2.csv', 'rb') as fin:
    reader = csv.DictReader(fin)
    data = {}
    for row in reader:
        for k, v in row.iteritems():
            if k in data:
                data[k] = [data[k],v]
            else:
                data[k] = v

And this returns:

{'Avg_Noshow': ['5.6', '4.5'],
 'Date': ['1-Apr-17', '2-Apr-17'],
 'Factory': ['A', 'A'],
 'Product_Number': ['1', '1'],
 'Room_Rev': ['275', '300'],
 'Walk_Cost': ['125', '200']}
like image 121
gold_cy Avatar answered Nov 15 '22 06:11

gold_cy