How to normalize a NumPy array to a unit vector?

To normalize a NumPy array to a unit vector, you can use the numpy.linalg.norm function to calculate the magnitude of the vector, and then divide the array by this magnitude. Here is an example code snippet:

import numpy as np

# Initialize an array
arr = np.array([1, 2, 3])

# Calculate the magnitude of the vector
magnitude = np.linalg.norm(arr)

# Normalize the array by dividing by the magnitude
unit_vec = arr / magnitude

print(unit_vec)

Watch a course Python - The Practical Guide

This will output [0.26726124 0.53452248 0.80178373]