def duration_in_mins(datum, city):
if city == 'Washington':
duration = round(int(datum['Duration (ms)']) /60000, 4)
else:
duration = round(int(datum['tripduration']) /60 ,4)
return duration
但是在调用此功能后,这给了我一个关键错误
def condense_data(in_file, out_file, city):
with open(out_file, 'w') as f_out, open(in_file, 'r') as f_in:
out_colnames = ['duration', 'month', 'hour', 'day_of_week', 'user_type']
trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames)
trip_writer.writeheader()
trip_reader =csv.DictReader(in_file)
for row in trip_reader:
new_point = {}
dur=duration_in_mins(row, city)
month,hour, day_of_week=time_of_trip(row, city)
type=type_of_user(row, city)
new_point={'duration':dur, 'month':month, 'hour':hour, 'day_of_week':day_of_week, 'user_type':type}
trip_writer.writerow(**new_point)
成功编译了condense_data函数,当我检查它是否正常工作时,我发现它给了我关键错误
KeyError: 'Duration (ms)'
答案 0 :(得分:0)
虽然代码写得不错,但是很难从您的代码中看出来,我根本不足以理解您的 exact 问题。但是,它可能像切换一样简单
duration = round(int(datum['Duration (ms)']) /60000, 4)
收件人:
duration = round(int(datum['duration']) /60000, 4)
同样,如果没有输入的csv格式,很难说出来,或者可能缺少一些代码。该链接最近帮助我解决了类似的错误:
https://wiki.python.org/moin/KeyError
这可能对您完全没有用,但我希望不是。编码愉快!而且,如果您澄清了自己的问题,我很乐意再次查看。