我的csvs包含以下标题行:“Participating_states”,“Number_of_participating_agencies”,“Population_covered”,“Agencies_submitting_incident_reports”,“Total_number_of_incidents_reported”。
我需要通过将第四列除以第二列来找到百分比,所以我找到了一个允许我这样做的Python脚本,并将百分比添加为第六列:
import csv
import tempfile
import shutil
input_file = '2000_percentage.csv'
with open(input_file, 'rb') as f, \
tempfile.NamedTemporaryFile(delete=False) as out_f:
reader = csv.reader(f)
writer = csv.writer(out_f)
writer.writerow(next(reader))
for row in reader:
try:
val1 = float(row[3])
val2 = float(row[1])
writer.writerows([row + [val1 / val2 * 100]])
except ValueError:
print('There are strings in this file.')
shutil.move(out_f.name, input_file)
此脚本完美无缺。我想要做的就是为在writer.writerows中添加的列添加列名([row + [val1 / val2 * 100]])。列名称应为“Reporting_percentage”。我正在使用Python 2.7.9。谢谢!