Numpy - and it's methods

Lesson#2 of 9 in project Theory

np.array() — Convert a list to an ndarray.

import numpy as np
a = np.array([1, 2, 3])
print(a)        # [1 2 3]
print(a.dtype)  # int64

np.zeros() / np.ones() — Fill an array with 0s or 1s.

np.zeros((3, 4))   # 3×4 array of 0.0
np.ones((2, 2))    # 2×2 array of 1.0
np.full((2,3), 7)  # fill with 7

np.arange() — Like Python range(), but returns an array.

np.arange(0, 10, 2)
# array([0, 2, 4, 6, 8])

np.linspace() — Evenly spaced values between two points.

np.linspace(0, 1, 5)
# array([0.  , 0.25, 0.5 , 0.75, 1.  ])

np.random.rand() — Random values in [0, 1).

np.random.rand(3, 3)      # uniform
np.random.randn(3, 3)     # normal (std)
np.random.randint(0,10,5) # int range

arr.reshape() — Change shape without changing data.

a = np.arange(12)
b = a.reshape(3, 4)
print(b.shape)  # (3, 4)

arr.flatten() / arr.ravel() — Collapse to 1D. flatten() copies, ravel() may not.

b = np.array([[1,2],[3,4]])
b.flatten()  # array([1, 2, 3, 4])
b.ravel()    # same, no copy

np.concatenate() — Join arrays along an axis.

a = np.array([1, 2])
b = np.array([3, 4])
np.concatenate([a, b])  # [1 2 3 4]
np.vstack([a, b])       # 2D stack rows
np.hstack([a, b])       # stack cols

arr.T / np.transpose() — Transpose rows and columns.

a = np.array([[1,2,3],[4,5,6]])
a.T
# array([[1, 4],
#        [2, 5],
#        [3, 6]])

np.sum() / np.mean() — Aggregate across all or one axis.

a = np.array([[1,2],[3,4]])
np.sum(a)         # 10
np.sum(a, axis=0) # [4, 6]  (cols)
np.mean(a)        # 2.5

np.min() / np.max() — Find extremes, or their indices.

a = np.array([3, 1, 4, 1, 5])
np.min(a)     # 1
np.max(a)     # 5
np.argmin(a)  # 1 (index)
np.argmax(a)  # 4 (index)

np.std() / np.var() — Standard deviation and variance.

a = np.array([2, 4, 4, 4, 5, 5, 7, 9])
np.mean(a)  # 5.0
np.std(a)   # 2.0
np.var(a)   # 4.0

np.dot() / @ — Matrix multiplication / dot product.

a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.dot(a, b)
# or just: a @ b
# array([[19, 22],
#        [43, 50]])

np.sort() / np.argsort() — Sort values or get sorted indices.

a = np.array([3, 1, 4, 1, 5])
np.sort(a)     # [1 1 3 4 5]
np.argsort(a)  # [1 3 0 2 4]

Boolean indexing — Filter with a condition mask.

a = np.array([1, 2, 3, 4, 5])
mask = a > 3
a[mask]      # array([4, 5])
a[a % 2 == 0] # array([2, 4])

np.where() — Conditional element selection.

a = np.array([1, -2, 3, -4])
np.where(a > 0, a, 0)
# array([1, 0, 3, 0])
np.where(a > 0)  # indices only
# (array([0, 2]),)

arr[::step] slicing — Slice rows, cols, strides.

a = np.arange(10)
a[2:7]     # [2 3 4 5 6]
a[::2]     # [0 2 4 6 8]
b = np.arange(9).reshape(3,3)
b[1:, :2]  # bottom-left 2×2

np.unique() — Unique values, counts, indices.

a = np.array([3,1,2,1,3,3])
np.unique(a)
# array([1, 2, 3])
np.unique(a, return_counts=True)
# (array([1,2,3]), array([2,1,3]))


And my own click-to-coopy example of numpy capabilities:

import numpy as np

def main():
    print("1. Array creation")
    arr = np.array([1, 2, 3, 4])
    print("  from list:", arr)
    
    python_array = [1, 2, 3, 4]
    
    # print(python_array == arr)

    zeros = np.zeros((2, 3))
    print("  zeros:")
    print(zeros)

    ones = np.ones((2, 3), dtype=np.int32)
    print("  ones:")
    print(ones)

    arange = np.arange(0, 10, 2)
    print("  arange:", arange)

    lin = np.linspace(0, 1, 5)
    print("  linspace:", lin)

    eye = np.eye(3)
    print("  eye (identity matrix):")
    print(eye)

    print("\n2. Reshape and type information")
    matrix = np.arange(12).reshape(3, 4)
    print("  reshape to (3, 4):")
    print(matrix)
    print("  dtype:", matrix.dtype)
    print("  shape:", matrix.shape)

    print("\n3. Indexing and slicing")
    print("  matrix[1]:", matrix[1])
    print("  matrix[0, 2]:", matrix[0, 2])
    print("  first two rows:")
    print(matrix[:2, :])
    print(matrix[:, :2])

    print("\n4. Boolean masking")
    mask = matrix % 2 == 0
    print("  even mask:")
    print(mask)
    print("  even values:", matrix[mask])

    print("\n5. Fancy indexing")
    rows = np.array([0, 2])
    cols = np.array([1, 3])
    print("  selected elements:", matrix[rows, cols])

    print("\n6. Vectorized operations")
    a = np.array([1, 2, 3], dtype=np.float64)
    b = np.array([4, 5, 6], dtype=np.float64)
    print("  a + b:", a + b)
    print("  a * b:", a * b)
    print("  a ** 2:", a ** 2)
    print("  sqrt(a):", np.sqrt(a))

    print("\n7. Broadcasting")
    x = np.array([
        [1, 2, 3], 
        [4, 5, 6]
    ])
    y = np.array([10, 20, 30])
    print("  x + y:")
    print(x + y)

    print("\n8. Aggregation and statistics")
    print("  sum:", matrix.sum())
    print("  mean:", matrix.mean())
    print("  axis 0 sum:", matrix.sum(axis=0))
    print("  axis 1 mean:", matrix.mean(axis=1))
    print("  standard deviation:", matrix.std())

    print("\n9. Linear algebra")
    m1 = np.array([[1.0, 2.0], [3.0, 4.0]])
    m2 = np.array([[5.0, 6.0], [7.0, 8.0]])
    print("  dot product:")
    print(np.dot(m1, m2))
    print("  matmul (@):")
    print(m1 @ m2)
    print("  transpose:")
    print(m1.T)
    print("  inverse:")
    print(np.linalg.inv(m1))
    print("  eigenvalues:", np.linalg.eigvals(m1))

    print("\n10. Random sampling")
    rng = np.random.default_rng(42)
    print("  random integers:", rng.integers(0, 10, size=5))
    print("  random normal:", rng.normal(loc=0.0, scale=1.0, size=(2, 3)))

    print("\n11. Saving and loading")
    tmp = np.arange(6).reshape(2, 3)
    np.savetxt("tmp_numpy_example.csv", tmp, delimiter=",", fmt="%d")
    print("  saved tmp_numpy_example.csv")
    loaded = np.loadtxt("tmp_numpy_example.csv", delimiter=",")
    print("  loaded back:")
    print(loaded)


if __name__ == "__main__":
    main()