Sanju Sanju - 5 months ago 9
Python Question

Extract data of a column by matching data of other column in Python

I want to extract all MaxTemp for year 2010

Year Month Day MaxTemp MinTemp
2010 1 1 -19.9 -37.2
2010 1 2 -13.8 -20
2010 1 3 -13.1 -15.9
2010 1 4 -12 -22.3
2010 1 5 -11.8 -14.4
2010 1 6 -14.3 -32.5
2010 1 7 -28.2 -37.3
2011 1 8 -21.9 -31.3
2011 1 9 -7.4 -22.8
2011 1 10 -6.6 -15.3
2011 1 11 -0.7 -15.2
2011 1 12 4.3 -5.8


my current code is

with open('data/'+file_name, "rU") as files:
val = list(csv.reader(files))[1:]


this extract whole csv without header. How can i accomplish the desired task of extracting all MaxTemp for only year 2010. Year I can pass as an argument. Thanks much.

Answer

As rofls said, but with comprehensions

with open('data/'+file_name, "rU") as files:
    data = [x[3] for x in csv.reader(files) if str(x[0]) == '2010']