T
T
tchainer2016-01-11 17:57:10
Python
tchainer, 2016-01-11 17:57:10

Print output to one column in python?

Guys, please help. I have a csv that looks like this:
435;fd;4
435;a;4
435;b lfdsk;2
435;c lfdsk;4
435;d;14
435;dsf;3
435;ad;4
435;fd;4
I need to use only the 3rd column (the separator is clear ;) and count how many times 1 element entered the column, i.e. the result should be something like this (the number of occurrences in the 1st column, the element itself in the other):
1;3
13;7
2;8
etc
And sort in descending order of the number of occurrences.
My code does not give 100% the result I need, alas:
#!/usr/bin/env python
import csv
import collections
grades = collections.Counter()
with open('Ya.csv') as input_file:
for row in csv.reader(input_file, delimiter=';'):
grades[row[2]] += 1
a= grades.most_common()
print(a[0])
print(a[1])
print(a [2])
print(a[3])
input_file.close()
Prints this:
('4', 5)
('3', 1)
('2', 1)
('14', 1)
On the command line this is a very trivial task, in python I just got tired ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2016-01-11
@nirvimel

If I understood the question correctly, then the problem is only in the formatted output.

print '\n'.join(('%s;%s' % (key, value) for key, value in grades.most_common()))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question