Rotan075
Rotan075

Reputation: 2615

Count the elements in a csv file with python

I got a question regarding counting the number of times a specific number belongs to a specific element.

Let me explain it better by use of an example. First I got this situation within my csv file: Capture from my csv file

What I want is that within Python I need to have the following results:

Can anyone help me getting this result?

Code that I have untill now is just loading the csv:

with open('calculate_ids.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=',', quotechar='|')

Upvotes: 2

Views: 4972

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

Use a Counter mapping the rows to tuples:

from collections import Counter
with open('calculate_ids.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=',', quotechar='|')
     counts = Counter(map(tuple,reader))

That Counter dict will count how many times the each pairing appears.

To see the counts just iterate over .items and you will see each pairing as the key and the count as the value:

for k, v in counts.items():
    print("{}  and {} are paired {} time(s)".format(k[0], k[1], v))

Upvotes: 2

Related Questions