python - KeyError读取CSV文件并将其传输到数组

原文 标签 python arrays csv

我有一个名为'r2.csv'的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
-------------------------------------------------------------------------

我有以下python代码来读取csv文件并将列传输到数组:
# 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)

除最后一行外,它运行正常,并显示以下错误消息:
File "<stdin>", line 1, in <module>
  KeyError: 'Room_Rev'

我怎么才能避免呢?

最佳答案

我无法使用此清理版本的代码再现问题:

# Read csv file
import csv
with open('r2.csv', 'r') as infile:
    reader = csv.DictReader(infile)
    data = {}
    for row in reader:
        print('row: {}'.format(row))
        for header, value in row.items():
            try:
                data[header].append(value)
            except KeyError:
                data[header] = [value]

print('')
from pprint import pprint
pprint(data)

# 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)

这是它产生的打印输出:
 row: {'Walk_Cost': '125', 'Factory': 'A', 'Avg_Noshow': '5.6', 'Product_Number': '1', 'Date': '01APR2017', 'Room_Rev': '275'}
 row: {'Walk_Cost': '200', 'Factory': 'A', 'Avg_Noshow': '4.5', 'Product_Number': '1', 'Date': '02APR2017', 'Room_Rev': '300'}
 row: {'Walk_Cost': '150', 'Factory': 'A', 'Avg_Noshow': '6.6', 'Product_Number': '1', 'Date': '03APR2017', 'Room_Rev': '250'}
 row: {'Walk_Cost': '175', 'Factory': 'A', 'Avg_Noshow': '7.5', 'Product_Number': '1', 'Date': '04APR2017', 'Room_Rev': '325'}

 {'Avg_Noshow': ['5.6', '4.5', '6.6', '7.5'],
  'Date': ['01APR2017', '02APR2017', '03APR2017', '04APR2017'],
  'Factory': ['A', 'A', 'A', 'A'],
  'Product_Number': ['1', '1', '1', '1'],
  'Room_Rev': ['275', '300', '250', '325'],
  'Walk_Cost': ['125', '200', '150', '175']}

这是我自己创建并使用的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

相关文章:

python - Django REST Framework教程1:序列化中的ImportError

php - 用PHP更新数组中的MySQL行

php - 使用LOAD DATA LOCAL INFILE将CSV文件加载到MySQL中时,如何限制CPU负载?

python - 使用python从csv替换和删除列

r - Sparklyr忽略行定界符

python - 计算多元正态分布python的均值向量

python - $ Windows换行符号(Python字节正则表达式)

python - matplotlib忽略丢失的数据

arrays - 在Swift 3中从字典中的数组中检索随机项

javascript - JavaScript-MVC.NET:获取多维数组的价值