Issue
I am trying to get the maximum value listed on a CSV file in one particular column. I cannot use pandas yet so everything has to be basic.
CSV sample data is:
grant 313 2014 grant 976 2013 grant 245 2012 grant 90 2011 grant 962 2010
Output needs to be: grant made 976 in 2013
--> which is the maximum value under the name
grant and the year was made.
My code is:
import csv
Empmax = input("Enter employee name: ")
maxMade = 0
with open("data.csv") as file:
reader = csv.reader(file)
for line in reader:
name = line[0]
year = line[1]
made = line[2]
if Empmax.lower() == name.lower():
if int(made) > maxMade:
maxMade = int(made)
print(Empmax, "made", maxMade, "in", int(year))
Output comes out like this: grant made 962 in 2010
.
Updated it and I got the max: I used: if int(made) > maxMade: from benny's example. Though year is still not updating.
Solution
Assuming you really want to read a CSV file, you'll want to change your data to be delimited by commas, like this:
grant,313,2014
grant,976,2013
grant,245,2012
grant,90,2011
grant,962,2010
Then, here's a version of your code that gives you the results you desire:
import csv
empName = input("Enter employee name: ")
maxMade = 0
maxYear = 0
with open("/tmp/data.csv") as file:
reader = csv.reader(file)
for line in reader:
name = line[0]
made = int(line[1])
year = line[2]
if empName.lower() == name.lower() and made > maxMade:
maxMade = made
maxYear = year
print(empName, "made", maxMade, "in", maxYear)
Result:
grant made 976 in 2013
If your data has spaces in it already and you don't want to change that, then you should use a regular file reader and then call split()
on each line of the file to get the individual fields. @BennyMue's answer shows how to do this.
If you don't use a CSV file and a CSV reader object, then I'd suggest that you change the extension on your data file and the names in your code to not use "csv", as doing that is misleading when you aren't actually reading CSV data.
Answered By - CryptoFool Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.