array([1, 2, 3, 4, 5])
NumPy and Arrays
Use NumPy arrays for quantitative calculations.
Learning Objectives
- Create NumPy arrays.
- Perform vectorized arithmetic.
- Compute basic summary statistics.
- Understand why arrays are useful for mathematical modeling.
Motivation
Lists are useful, but quantitative work usually needs fast operations over many numbers. NumPy arrays make those operations concise and efficient.
Creating Arrays
Vectorized Arithmetic
When you multiply an array by 2, NumPy multiplies every element.
array([ 2, 4, 6, 8, 10])
This is different from a Python list:
[1, 2, 3, 1, 2, 3]
Summary Statistics
(np.float64(3.0), np.int64(1), np.int64(5), np.int64(15))
The package includes a reusable summary helper.
ArraySummary(shape=(5,), mean=3.0, minimum=1.0, maximum=5.0, total=15.0)
Common Mistakes
Expecting Lists and Arrays to Behave the Same Way
[1, 2, 3] * 2 repeats a list. np.array([1, 2, 3]) * 2 doubles each value.
Ignoring Shape
Array shape tells you the dimensions of the data. Many numerical errors come from using arrays with incompatible shapes.
Practice
- Create an array with values
[10, 20, 30]. - Divide every value by
10. - Compute the mean.
- Use
array_summary(...)on the array.
Solutions
TipSolution 1
Answer:
import numpy as np
values = np.array([10, 20, 30])
TipSolution 2
Answer: array([1., 2., 3.]).
values / 10
TipSolution 3
Answer: 20.0.
The mean is (10 + 20 + 30) / 3 = 20.
TipSolution 4
Answer:
from fcmath.python_fundamentals import array_summary
array_summary(values)