Answer the question
In order to leave comments, you need to log in
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)
import csv
f = open('input','r', encoding='UTF-8')
l = [int(i['num']) for i in csv.DictReader(f)]
print(max(l))
Answer the question
In order to leave comments, you need to log in
Look in the direction of the 'pandas' library there and the choice of the maximum and reading by columns.
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.
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 questionAsk a Question
731 491 924 answers to any question