we wanted to find the maximum grade for each students exams then we can use the

We wanted to find the maximum grade for each students

This preview shows page 13 - 15 out of 15 pages.

12
Image of page 13
np.where(condition, arr if true, arr if false) - returns an array in which the elements are replaced or unchanged based on a provided condition. Consider the grades array used previously. >>> grades = np.array([[90, 87, 96], [79, 100, 92], [98, 60, 74]]) If we want to find all grades that are greater than or equal to a 90 and replace the score with an “A” and leave all other values the same we can accomplish this using the following >>> np.where(grades >= 90, "A", grades) array([['A', '87', 'A'], ['79', 'A', 'A'], ['A', '60', '74']] If we want to find all grades that are greater than or equal to a 90 and replace the score with an “A” and replace all other values with “Not A” we can accomplish this using the following >>> np.where(grades >= 90, "A", "Not A") array([['A', 'Not A', 'A'], ['Not A', 'A', 'A'], ['A', 'Not A', 'Not A']] Now more realistically, what if we wanted to replace all grades with the letter grade equivalent. We can do this by using nested np.where functions. >>> np.where(grades >= 90, "A", np.where(grades >= 80, "B", np.where(grades >= 70, "C", np.where(grades >= 60, "D", "F") ) ) ) array([['A', 'B', 'A'], 13
Image of page 14
['C', 'A', 'A'], ['A', 'D', 'C']]) np.loadtxt(open("fileName"), delimiter = " ", skiprows = 0, usecols = none, dtype = float) - Returns an array of values read from a file (typically txt, csv, or tsv) Imagine a file named grades.csv . Exam 1,Exam 2,Exam 3 90,87,96 79,100,92 98,60,74 To convert this information into a numpy array, use loadtxt . >>> grades = np.loadtxt(open("grades.csv"), delimiter = ",", skiprows = 1, dtype = "int32") >>> grades array([[90, 87, 96], [79, 100, 92], [98, 60, 74]]) np.savetxt("fileName.extension", array, delimiter = " ", newline = "\n", header = "", comments = "") - Writes an array to a file Suppose we wanted to write grades to a tsv file. We can do this using the following >>> np.savetxt("grades.tsv", arr, delimiter = "\t", newline = "\n", header = "Exam 1\tExam 2\tExam 3", comments = "") Resources 14
Image of page 15

You've reached the end of your free preview.

Want to read all 15 pages?

  • Fall '08
  • THOMAZ
  • Boolean Algebra, Array, Bitwise operation, NumPy, Array Properties

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture