0

Here is my data.csv

a,1,1-Jan-2017
a,2,3-Jan-2017
a,4,14-Feb-2017
b,21,1-Dec-2016
b,7,28-Nov-2016

My target is to print below as final list. Format is unique(first_column),no.of occurences

a,3
b,2 

Written below python script but unable to enter second block to print 'second block' although the same logic works fine in previous loop.

import csv

with open('/home/user/python/data.csv') as csvfile :
    DataCaptured = csv.reader(csvfile,delimiter=',')
    UniqueValues = []
    FinalList = []

    for row in DataCaptured :
            if row[0] not in UniqueValues :
                    UniqueValues.append(row[0])

    print 'Unique values are:\n' + str(UniqueValues)

    for unique in UniqueValues :
            counter = 0
            print 'First block',unique
            for row in DataCaptured :
                    print 'Second block'
                    if unique == row[0] :
                            counter = int(counter)+1
            FinalList.append(unique+','+str(counter))

    print 'Final list:\n' + str(FinalList)
2
  • Here is my data.csv a,1,1-Jan-2017 a,2,3-Jan-2017 a,4,14-Feb-2017 b,21,1-Dec-2016 b,7,28-Nov-2016 Commented Feb 17, 2017 at 19:34
  • 2
    DataCaptured is a reader object. Not an reusable list. Check documentation first. Commented Feb 17, 2017 at 19:40

2 Answers 2

4

It's because you've already read over the entire file after the first loop; there are no more rows in the reader's iterator at this point. Use csvfile.seek(0) after the first for loop to return to the beginning of the file, and it will work.

Sign up to request clarification or add additional context in comments.

Comments

1

You could simplify the program above a bit and only iterate through the file once:

import csv

with open('/home/user/python/data.csv') as csvfile :
    unique_values = {}

    for row in csv.reader(csvfile, delimiter=','):
        element = row[0]
        if element not in unique_values:
            unique_values[element] = 0

        unique_values[element] += 1

    for unique, count in unique_values.items():
        print('{0},{1}'.format(unique, count))

1 Comment

You could also make use of collections.Counter

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.