Brosef
Brosef

Reputation: 3095

Referring to CSV header string to adjust column format

I'm somewhat new to python and csv processing, but I couldn't find any solutions for what I'm looking for. When I open up a specific CSV file in excel, I have a column called "rate" that is in percent. I'm dividing all the values in this column by 100. As of now I'm referring to this column by calling row[6] = percentToFloat(row[6]). My question is if its possible to address the row by the header name rather than just the column number.

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)

Upvotes: 2

Views: 116

Answers (4)

Ferit
Ferit

Reputation: 9657

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)

Updated.

Upvotes: 0

Severin Pappadeux
Severin Pappadeux

Reputation: 20080

You could use data frames from 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)

Upvotes: 2

karlson
karlson

Reputation: 5433

Use csv.DictReader instead of csv.reader.

Upvotes: 0

masnun
masnun

Reputation: 11906

Use csv.DictReader :

reader = csv.DictReader(inFile)

Now you can use row['column_name'] instead of row[6] in your code.

Upvotes: 1

Related Questions