Python Forum
Help iterating through DictReader loaded from csv
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help iterating through DictReader loaded from csv
#3
Thanks, Larz60+.

I'll try the list.
I'm new to Python and am still figuring out how to specify the columns in the code. I don't know if I use header name or an index at this point.

import csv
eat_count = 0
no_eat_count = 0
with open(r'C:\Users\delliott\Desktop\pythoncsv\Q3\eat.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        #the inner loop is still incorrect
        #I'm not sure if I can use the column names instead of indexes with lists
        for k in row['person_id']:
            if 'check_in' not in row ['type']:
                if 'cancelled' not in row ['type']:
                    eat_count += 1
                    break
        else:
           no_eat_count += 1
print('eat count = ' + str(eat_count))
print('no eat count = ' + str(no_eat_count))
I'll appreciate any suggestions using either the list or OrderedDict. I'll later try using Pandas.

OK, I see how to specify the columns using indexes... row [1].

Now I have...
import csv
eat_count = 0
no_eat_count = 0
with open(r'C:\Users\delliott\Desktop\pythoncsv\Q3\eat.csv', 'r') as f:
    reader = csv.reader(f)
    next(reader, None)  # skip the headers
    for row in reader:
        #the inner loop is still incorrect
        #I don't know how to loop through each person_id
        for k in row[0]:
            if 'check_in' not in row [1]:
                if 'cancelled' not in row [1]:
                    if row [1] != "":
                        eat_count += 1
                        print(row)
                        break
        else:
           no_eat_count += 1
print('eat count = ' + str(eat_count))
print('no eat count = ' + str(no_eat_count))
The incorrect output...
eat count = 8
no eat count = 9

It should be...
eat count = 3
no eat count = 3

The rows counted in eat count...
['90', 'brunch', '2/15/2018', '2/15/2018']
['90', 'lunch ', '2/15/2018', '2/15/2018']
['90', 'breakfast ', '2/15/2018', '2/22/2018']
['50', 'breakfast ', '2/15/2018', '2/26/2018']
['50', 'lunch ', '2/15/2018', '3/1/2018']
['60', 'dinner', '2/15/2018', '2/15/2018']
['60', 'lunch ', '2/21/2018', '2/21/2018']
['60', 'breakfast ', '3/15/2018', '3/15/2018']

Each person_id should only be counted once. I'm not sure how to do that inner loop on person_id in Python. I was attempting to loop through and then break out of the inner loop once the eat_count is incremented.
Can I get any suggestions?
Reply


Messages In This Thread
RE: Help iterating through DictReader loaded from csv - by Huck - May-01-2018, 07:33 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020