Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python collections.Counter

Tags:

python-2.7

New to python and wondering how can I tell python that the data in row 3 are all one number not individual numbers? I am using collections.Counter but it may not be the correct thing.

datafile.csv
Z4,29-Mar-13,Name 1,1234567
Z4,30-Mar-13,Name 1,1234567
Z4,1-Apr-13,Name 1,1234567
Z1,30-Mar-13,Name 2,1234568
Z1,1-Apr-13,Name 2,1234568
Z1,30-Mar-13,Name 3,1234569
Z2,28-Mar-13,Name 5,1234577
Z3,28-Mar-13,Name 4,1234570
Z3,29-Mar-13,Name 4,1234570
Z3,30-Mar-13,Name 4,1234570
Z3,1-Apr-13,Name 4,1234570
Z3,2-Apr-13,Name 4,1234570

datafiletotals.py

import csv
import collections

for row in csv.reader(open('datafile.csv')):
        print collections.Counter(row[3])

This is what my output currently is:

python datafiletotals.py

Counter({'1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1, '6': 1})
Counter({'1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1, '6': 1})
Counter({'1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1, '6': 1})
Counter({'1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '6': 1, '8': 1})
Counter({'1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '6': 1, '8': 1})
Counter({'1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '6': 1, '9': 1})
Counter({'7': 2, '1': 1, '3': 1, '2': 1, '5': 1, '4': 1})
Counter({'1': 1, '0': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1})
Counter({'1': 1, '0': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1})
Counter({'1': 1, '0': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1})
Counter({'1': 1, '0': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1})
Counter({'1': 1, '0': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1})

This is what I would like it to look like.

1234567,3
1234568,2
1234569,1
1234577,1
1234570,5
like image 755
ncphotos2000 Avatar asked Sep 05 '25 03:09

ncphotos2000


1 Answers

I think you want

>>> import csv, collections
>>> 
>>> with open("datafile.csv", "rb") as fp:
...     reader = csv.reader(fp)
...     counts = collections.Counter(row[3] for row in reader)
...     
>>> counts
Counter({'1234570': 5, '1234567': 3, '1234568': 2, '1234569': 1, '1234577': 1})

Right now, you're not making one Counter object, you're asking for a Counter object for each row, and each instance is counting the characters in row[3].

like image 136
DSM Avatar answered Sep 07 '25 23:09

DSM