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
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With