11. NumPy Operations
Element-wise Operations
NumPy applies operations to every element:
arr = np.array([1, 2, 3, 4, 5])
print(arr + 10) # [11, 12, 13, 14, 15]
print(arr * 2) # [2, 4, 6, 8, 10]
print(arr ** 2) # [1, 4, 9, 16, 25]
print(arr / 2) # [0.5, 1.0, 1.5, 2.0, 2.5]
Array-to-Array Operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # [5, 7, 9]
print(a * b) # [4, 10, 18]
print(a - b) # [-3, -3, -3]
Reduction Operations
arr = np.array([1, 2, 3, 4, 5])
print(arr.sum()) # 15
print(arr.mean()) # 3.0
print(arr.std()) # 1.414... (population std)
print(arr.min()) # 1
print(arr.max()) # 5
print(arr.prod()) # 120 (1*2*3*4*5)
Axis Operations
For 2D arrays, specify the axis:
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.sum(axis=0)) # [5, 7, 9] (sum columns)
print(matrix.sum(axis=1)) # [6, 15] (sum rows)
print(matrix.mean(axis=1)) # [2.0, 5.0]
Comparison and Masking
arr = np.array([1, 5, 3, 8, 2])
mask = arr > 3
print(mask) # [False, True, False, True, False]
print(arr[mask]) # [5, 8] (fancy indexing)
# Combined
print(arr[arr % 2 == 0]) # [1, 3, 2] -> even values only
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Create an array of 20 random numbers. Calculate the mean, standard deviation, and find all values within one standard deviation of the mean.