Numpy Examples in Python

Numpy

Euclidean Norm (np.linalg.norm)

import numpy as np

A = np.array([[1, 2], [1, 3]])
print(A)
# Output:
# [[1 2]
#  [1 3]]

norms = np.linalg.norm(A, axis=1)
print(norms)
# Output: [2.23606798 3.16227766]

Vectorize Functions

np.vectorize allows you to apply a function element-wise to arrays (like a generalized map):

import numpy as np

def my_func(x):
    return x ** 2 + 1

vec_func = np.vectorize(my_func)
arr = np.array([1, 2, 3])
print(vec_func(arr))
# Output: [2 5 10]

Common Numpy Operations

import numpy as np

# Create arrays
a = np.array([1, 2, 3])
b = np.zeros((2, 3))
c = np.ones((3, 3))
d = np.eye(3)  # Identity matrix

# Array math
sum_ab = a + np.array([4, 5, 6])
product = a * 2

# Broadcasting
arr = np.arange(6).reshape(2, 3)
broadcasted = arr + np.array([10, 20, 30])

# Slicing
sub = arr[:, 1:]

Useful Numpy Tips

  • Use np.mean, np.std, np.sum, etc., for fast statistics.
  • Use boolean indexing for filtering: a[a > 1].
  • Use np.dot or @ for matrix multiplication.
  • Use np.concatenate, np.vstack, np.hstack to combine arrays.

References and Tutorials