Numpy Fundamentals

Create an array

Numpy creates objects of type numpy.ndarray

# Create basic array from Python list
np.array([1, 2, 3, 4, 5])

# Create array from range
np.array(range(500))

Compute dot product

Computes dot product

  • For 1D arrays it is inner product of vectors

  • For 2D arrays it is element-wise matrix multiplication (using matmul or a @ b is preferred)

  • For 0D scalars it is multiplication (a * b is preferred)

# Dot product
np.dot(a, b)


# Dot product using low-level operations)
(a * b).sum()

Create 2D array

Numpy can work with n-dimensional arrays

# 2D array
np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

Create linear space

To create an ndarray of numbers over a specified interval

# Create 50 numbers between 1 and 100
np.linspace(1, 100, 50) 

# Create 100 numbers between -50 and 50
np.linspace(-50, 50, 100)

# Create 20 numbers, don't include the end interval
np.linspace(1, 100, 20, False)

Last updated