A
A
Andrey Kazantsev2017-03-28 06:14:03
Python
Andrey Kazantsev, 2017-03-28 06:14:03

How to get a specific column from a csv file in python?

I need to write a program to find the maximum value in the num column in a csv file. I wrote such a program

f = open('input','r', encoding='UTF-8').read().split('\n')
f = [i for i in f if len(i)!=0]
num = f[0].split(',').index("num")
ans = int(f[1].split(',')[num])
for string in f[2:]:
    number = int(string.split(',')[num])
    ans = number if number > ans else ans
print(ans)

However, it fails all tests. Where is the mistake.
PS There is another
import csv
f = open('input','r', encoding='UTF-8')
l = [int(i['num']) for i in csv.DictReader(f)]
print(max(l))

But an error in the same tests.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
gill-sama, 2017-03-28
@gill-sama

Look in the direction of the 'pandas' library there and the choice of the maximum and reading by columns.

S
SkiBY, 2017-03-28
@SkiBY

You need to divide the rows right away, for example like this, since the csv library is in the case
x = csv.reader(f, delimiter=';') - here you need to clearly understand that you have a divider in the file
and then through the "for row in" loop x", row[0] is the first column. Create an array, look for the maximum, etc.

Q
qlkvg, 2017-03-28
@qlkvg

1. Read the csv the way SkiBY suggested
2. Transpose the matrix. There are a lot of recipes here , the easiest and without unnecessary dependencies - [list(i) for i in zip(*A)]
After transposition, it will be possible to work with columns directly by index. Accordingly, it will be easy to find the maximum - max(i[<column index>])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question