Python Forum
Filtering with IF Statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Filtering with IF Statement
#11
csv.DictReader will create dictionary for every row according to mapping. If table in csv file is in table format it's maps to first row, but as your file is 'headless' then you should provide headers separately.

What good it does? Instead of indices you can use dictionary keys. As far as I understand, only four datapoints per row is needed (other data is mapped to underscores):

>>> from csv import DictReader
>>> headers = ['Disease', '_', 'State', 'Instances', '__', 'Year']
>>> with open('health_no_head_sample.csv', 'r', encoding='UTF-8') as f:
...     data = list(DictReader(f, fieldnames=headers))
...
>>> data[:2]
[OrderedDict([('Disease', 'MEASLES'),
              ('_', '206.98'),
              ('State', 'COLORADO'),
              ('Instances', '2099'),
              ('__', '1014000'),
              ('Year', '1928')]),
 OrderedDict([('Disease', 'MEASLES'),
              ('_', '634.95'),
              ('State', 'CONNECTICUT'),
              ('Instances', '10014'),
              ('__', '1577000'),
              ('Year', '1928')])]
>>> [row for row in data if row['State'] == 'COLORADO']
[OrderedDict([('Disease', 'MEASLES'),
              ('_', '206.98'),
              ('State', 'COLORADO'),
              ('Instances', '2099'),
              ('__', '1014000'),
              ('Year', '1928')]),
 OrderedDict([('Disease', 'POLIO'),
              ('_', '7.04'),
              ('State', 'COLORADO'),
              ('Instances', '71'),
              ('__', '1014000'),
              ('Year', '1928')]),
 OrderedDict([('Disease', 'SMALLPOX'),
              ('_', '33.58'),
              ('State', 'COLORADO'),
              ('Instances', '340'),
              ('__', '1014000'),
              ('Year', '1928')]),
/..../
>>> [row['State'], row['Disease'], row['Instances'], row['Year'] for row in data if row['State'] == 'COLORADO' and row['Year'] == '1929']
[('COLORADO', 'MEASLES', '748', '1929'),
 ('COLORADO', 'POLIO', '13', '1929'),
 ('COLORADO', 'SMALLPOX', '844', '1929')]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

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