2

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:

  • 1 with 1200 is 4 (times visible)
  • 1 with 5600 is 5 (times visible)
  • 2 with 1400 is 3 (times visible)
  • 2 with 1600 is 2 (times visible)

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='|')

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks! :) I am going to try this out!! Will reply if it worked! Thanks! :)
@Rotan075, no worries, the only issue is if the numbers can appear it either column, do the numbers in each column ever overlap?
The csv file does not contain like: 1,1 (column1,column2). like the same value for colum1 and column2 does not appear. The scenario of having: 1,2 and later on the csv file 2,1 does occur. Is that a problem?
@Rotan075, it depends on what you want to do, are 1,2 and 2,1 the same or considered a different pairing?
Thanks for the explanation! I will mark your answer! :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.