0

I have a CSV file that looks like this:

    Values   Dates
      10      3/17
      20      4/17
      40      5/17

My goal is to loop through the "Values" column and find the differences between each row, and as a bonus find the average difference between rows. I am familiar with VBA code for excel, in which I would just use i - (i - 1), but that doesn't translate too well to Python. So far, my code looks like:

import csv
import os 

changes = []

os.path.join("Path", "To", "File")
with open(file) as dFile:
    reader = csv.reader(dFile)
    next(reader)

    for row in reader:
        change = row[0] - (row-1)[0]
        changes.append(change)

I didn't really expect this to work but not sure how to interact with the previous row in a loop. Any ideas?

ianhousman
  • 13
  • 2

2 Answers2

1

Just for completeness' sake:

I would just use i - (i - 1), but that doesn't translate too well to Python

That translates to Python just fine, but you have to create a list of rows first:

with open(file) as dFile:
    reader = csv.reader(dFile)
    next(reader)

    rows = list(reader)
    for i in range(1, len(rows)):
        change = rows[i][0] - rows[i-1][0]
        changes.append(change)

That's why the generator-based solutions proposed in the linked question are generally better.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • yup you got it, only thing I had to change from this code was this line: `change = int(rows[i][0]) - int(rows[i-1][0])` Thanks for the help! – ianhousman Feb 21 '20 at 09:43
0

You can add one more variable (prev_row) before the for-loop:

changes = []
with open('sample.csv') as dFile:
    reader = csv.reader(dFile)
    next(reader)

    prev_row = 0
    for row in reader:
        change = int(row[0]) - prev_row
        prev_row = int(row[0])
        changes.append(change)

The result will be:

changes = [10, 10, 20]
Djordje
  • 124
  • 7