Aggregate Operations, Array Indexing, Array Slicing
Aggregate (Reduction) Operations
Aggregate functions reduce an array to a single summary value.
import numpy as np
a = np.array([12, 45, 7, 23, 56, 9])
print(a.sum()) # 152
print(a.min()) # 7
print(a.max()) # 56
print(a.mean()) # 25.333...
print(a.std()) # standard deviation
print(a.var()) # variance
print(np.median(a)) # 17.5
print(a.argmax()) # 4 -- index of the max value
print(a.argmin()) # 2 -- index of the min value
Aggregates on 2D arrays (row-wise / column-wise using axis)
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.sum()) # 21 -- total of all elements
print(m.sum(axis=0)) # [5 7 9] -- column-wise sum (down each column)
print(m.sum(axis=1)) # [6 15] -- row-wise sum (across each row)
print(m.max(axis=0)) # [4 5 6]
axis=0 -> operate DOWN the columns (result has 1 value per column)
axis=1 -> operate ACROSS the rows (result has 1 value per row)
---
Array Indexing
a = np.array([10, 20, 30, 40, 50])
print(a[0]) # 10 (first)
print(a[-1]) # 50 (last)
m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(m[0, 0]) # 1 (row 0, col 0)
print(m[1, 2]) # 6 (row 1, col 2)
print(m[-1, -1]) # 9 (last row, last col)
Boolean (fancy) indexing
a = np.array([5, 12, 8, 20, 3])
print(a[a > 10]) # [12 20] -- only elements greater than 10
---
Array Slicing
a = np.array([10, 20, 30, 40, 50, 60])
print(a[1:4]) # [20 30 40]
print(a[:3]) # [10 20 30]
print(a[::2]) # [10 30 50]
print(a[::-1]) # [60 50 40 30 20 10]
Slicing a 2D array
m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(m[0:2, 1:3])
# [[2 3]
# [5 6]]
print(m[:, 1]) # [2 5 8] -- entire column 1
print(m[1, :]) # [4 5 6] -- entire row 1
Important: array slices are views, not copies — modifying a slice modifies the original array too. Use .copy() to get an independent copy.
a = np.array([1, 2, 3, 4, 5])
b = a[1:3]
b[0] = 999
print(a) # [1 999 3 4 5] -- original changed!