Python Warm-up 01 Numpy
- Tung San
- Jul 26, 2021
- 2 min read

Numpy warm-up
data = [50,50,47,97,49,3,53,42,26,74,82,62,37,15,70,27,36,35,48,52,63,64] print(data)
--- [50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15, 70, 27, 36, 35, 48, 52, 63, 64]
A Python list structure. But not optimized for numeric analysis. Use NumPy.
import numpy as np grades = np.array(data) print(grades)
--- [50 50 47 97 49 3 53 42 26 74 82 62 37 15 70 27 36 35 48 52 63 64]
A NumPy array.
print (type(data),'x 2:', data * 2) print('---') print (type(grades),'x 2:', grades * 2)
--- <class 'list'> x 2: [50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15, 70, 27, 36, 35, 48, 52, 63, 64, 50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15, 70, 27, 36, 35, 48, 52, 63, 64]
--- <class 'numpy.ndarray'> x 2: [100 100 94 194 98 6 106 84 52 148 164 124 74 30 140 54 72 70 96 104 126 128]
They give different results when '*' by 2.
print(grades.shape, grades[0], grades.mean())
--- (22,) 50 49.18181818181818
# Define an array of study hours study_hours = [10.0,11.5,9.0,16.0,9.25,1.0,11.5,9.0,8.5,14.5,15.5, 13.75,9.0,8.0,15.5,8.0,9.0,6.0,10.0,12.0,12.5,12.0]
# Create a 2D array (an array of arrays) student_data = np.array([study_hours, grades])
# display the array student_data
--- array([[10. , 11.5 , 9. , 16. , 9.25, 1. , 11.5 , 9. , 8.5 , 14.5 , 15.5 , 13.75, 9. , 8. , 15.5 , 8. , 9. , 6. , 10. , 12. , 12.5 , 12. ], [50. , 50. , 47. , 97. , 49. , 3. , 53. , 42. , 26. , 74. , 82. , 62. , 37. , 15. , 70. , 27. , 36. , 35. , 48. , 52. , 63. , 64. ]])
# Show shape of 2D array student_data.shape
--- (2, 22)
The student_data array contains two elements, each of which is an array containing 22 elements.
# Show the first element of the first element student_data[0][0]
--- 10.0
# Get the mean value of each sub-array avg_study = student_data[0].mean() avg_grade = student_data[1].mean() print('Average study hours: {:.2f}\nAverage grade: {:.2f}'.format(avg_study, avg_grade))
--- Average study hours: 10.52
--- Average grade: 49.18
Comments