我对python和csv处理有点新,但我找不到任何我正在寻找的解决方案。当我在excel中打开一个特定的CSV文件时,我有一个名为“rate”的列,以百分比表示。我将此列中的所有值除以100.截至目前,我通过调用row[6] = percentToFloat(row[6])
来引用此列。我的问题是它是否可以通过标题名称而不仅仅是列号来处理行。
with open(input) as inFile:
reader = csv.reader(inFile)
reader.next()
with open(output, 'w') as outFile:
writer = csv.writer(outFile)
for row in reader:
if len(row)>1: #skips empty rows
row[6] = percentToFloat(row[6])
writer.writerow(row)
答案 0 :(得分:2)
您可以使用Pandas的数据框
import pandas as pd
import numpy as np
df = pd.read_csv('data.csv', header=True)
print(df)
print(df.rate)
print(df.rate/100.0)
答案 1 :(得分:1)
答案 2 :(得分:0)
使用csv.DictReader代替csv.reader
。
答案 3 :(得分:0)
with open(input) as inFile:
reader = csv.DictReader(inFile)
rate_index = reader.fieldnames.index('rate')
reader.next()
with open(output, 'w') as outFile:
writer = csv.DictWriter(outFile, fieldnames=reader.fieldnames)
for row in reader:
if len(row)>1: #skips empty rows
row[rate_index] = percentToFloat(row[6])
writer.writerow(row)
更新