-1

So I have a function that finds the maximum value in a column in a csv file. I want to print the value thats on the same row as the max value, but in column 13. The code makes it clearer:

def bigQuake(inputfilename):

    file = open(inputfilename,"r")
    maxvalue = 0.0
    for line in file:
        value = line.split()
        try:
            p = float(line.split(",")[4])
            maxvalue = max(maxvalue,p)
        except:
            pass
return maxvalue

The code above simply finds the maxvalue of column 4, what's not working is when I replace

return maxvalue

with

print("The largest earthquake was a " + maxvalue + "magnitude earthquake" + value[12])

value[12] is trying to find the value in column 12 that corresponds to the max value of column 4. Note that column 12 contains strings, so I want the output to look like this:

>>>bigQuake(file.csv)
>>>The largest earthquake was a 50 magnitude earthquake 10km from San Francisco.
AspirationZ
  • 39
  • 1
  • 8
  • Can you please [edit] this to correctly format your code? As it's written this doesn't even run. Also: what's your actual question? What's not working? – Henry Keiter Mar 31 '14 at 02:43
  • The `def bigQuake...` should be in the code block. – Paul Mar 31 '14 at 02:44
  • This looks trivial with the `pandas` library. See http://stackoverflow.com/questions/10202570/pandas-dataframe-find-row-where-values-for-column-is-maximal ; You'd need to use `df = pandas.read_csv(fname) ` to get the data into a pandas data frame. – Paul Mar 31 '14 at 02:46
  • code fixed, my apologies – AspirationZ Mar 31 '14 at 02:49

1 Answers1

0

Track the value of magnitude corresponding to the maximum value in the 4th column.

Also better use csv module from standard library for parsing csv files:

import csv

def bigQuake(inputfilename):
    with open(inputfilename,"r") as input_file:
        reader = csv.reader(input_file)

        maxvalue = 0.0
        magnitude = None
        for line in reader:
            try:
                p = float(line[4])
                if p > maxvalue:
                    maxvalue = p
                    magnitude = line[12]
            except ValueError:
                pass

    print("The largest earthquake was a", maxvalue, "magnitude earthquake", magnitude, ".")

Also, note that you should use with context manager while working with files and catch only specific to situation exceptions.

Hope that helps.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195