We can create a numpy array from separate lists by specifying a format for each field: roster = np.zeros(4, dtype={'names': ('name', 'age', 'major', 'gpa'), 'formats': ('U50', 'i4', 'U4', 'f8')}) roster['name'] = ['Alice', 'Bob', 'Carol', 'Dennis'] roster['age'] = [21, 25, 18, 29] roster['major'] = ['CS', 'Math', 'Chem', 'Phys'] roster['gpa'] = [3.8, 3.2, 4.0, 3.5] where U50 is a string of max length 50, i4 is a 4-byte integer, U4 is a string of max length 4, and f8 is an 8-byte floating-point number. Then roster has value array([('Alice', 21, 'CS', 3.8), ('Bob', 25, 'Math', 3.2), ('Carol', 18, 'Chem', 4. ), ('Dennis', 29, 'Phys', 3.5)], dtype=[('name', '
We can create a numpy array from separate lists by specifying a format for each field:
roster = np.zeros(4, dtype={'names': ('name', 'age', 'major', 'gpa'), 'formats': ('U50', 'i4', 'U4', 'f8')})
roster['name'] = ['Alice', 'Bob', 'Carol', 'Dennis']
roster['age'] = [21, 25, 18, 29]
roster['major'] = ['CS', 'Math', 'Chem', 'Phys']
roster['gpa'] = [3.8, 3.2, 4.0, 3.5]
where U50 is a string of max length 50, i4 is a 4-byte integer, U4 is a string of max length 4, and f8 is an 8-byte floating-point number. Then roster has value
array([('Alice', 21, 'CS', 3.8), ('Bob', 25, 'Math', 3.2),
('Carol', 18, 'Chem', 4. ), ('Dennis', 29, 'Phys', 3.5)],
dtype=[('name', '<U50'), ('age', '<i4'), ('major', '<U4'), ('gpa', '<f8')])
Then, for example, roster['name'] will give an array of just the student names.
Write a program that reads the numpy array roster we just created that has this format:
name,age,major,gpa
Convert this to a numpy array as shown above. Then use that array to compute and print each of the following:
- The average GPA of all students
- The maximum GPA of students majoring in CS
- The number of students with a GPA over 3.5
- The average GPA of students who are at least 25 years old
- The major that has the highest average GPA among students at most 22 years old
For example, for the four students listed, your program should print:
3.625
3.8
2
3.35
Chem
Step by step
Solved in 4 steps with 2 images