Editing a CSV to keep only the first instance of an object.

I am self learning python and am only into my 2nd month. I have a csv that I want to remove/delete rows in. Here is an example of what it looks like.

subject,date,site,code,descrip

s1,date1,xxx,yyy,zzz

s1,date2,xxx,yyy,zzz

s1,date3,xxx,yyy,zzz

s2,date1,xxx,yyy,zzz

s2,date2,xxx,yyy,zzz

s3,date1,xxx,yyy,zzz

and it goes on for about 10000 subjects each with random amounts of dates for each subject. What I need is to keep the first instance for each subject and remove the rest. So that each subject has only one date, the earliest date. I have sorted it by date from the earliest to the latest so its not as clean as I have stated. I have tried some commands I found on stackoverflow but what I tried has removed all instances so I am left with a random assortment of subjects.

Posted Nov 19, 2019, 3:28 PM UTC

14
num8lock[0] not a clue•

Use csv.DictReader from csv module.

Make an empty dict, say result_subjects. Iterate the rows that's now are OrderDicts, only store the subject entry value as a key if it's not already in result_subjects dict, then store the rest as its value.

you'll end up with something like this

>>> print(result_subjects)
{
's1': OrderedDict([('date', 'date1'),
                ('site', 'xxx'),
                ('code', 'yyy'),
                ('descrip', 'zzz')]),
's2': OrderedDict([('date', 'date1'),                    
                ('site', 'xxx'),
                ('code', 'yyy'),
                ('descrip', 'zzz')]),
's3': OrderedDict([('date', 'date1'),
                 ('site', 'xxx'),
                ('code', 'yyy'),
                ('descrip', 'zzz')])
}
1
unknown47OP•

Sorry, this kinda flew over my head, but from what I understand you are saying to create and empty dict then send all the rows to it after being sorted, so that is now OrderDicts. Then you lost me.

The print statement doesn't look like what I need but if it only has the earliest date it will work, I think.

1
num8lock[0] not a clue•

I have sorted it by date from the earliest to the latest so its not as clean as I have stated.

i just presumed you already had the data sorted. csv.dictreader is returning rows as OrderDicts up to v3.7 https://docs.python.org/3/library/csv.html#csv.DictReader

1
unknown47OP•

I used this command to sort the csv by date

sort = sorted(csv1,key=operator.itemgetter(1))

1