Search⌘ K

NumPy Basics

Explore the fundamental NumPy operations to create and manipulate arrays effectively. Understand how to generate ranged data with arange and linspace, reshape and flatten arrays, transpose dimensions, and create arrays filled with zeros or ones. This lesson equips you with practical skills to handle multidimensional data for machine learning projects.

Chapter Goals:

  • Learn about some basic NumPy operations
  • Write code using the basic NumPy functions

A. Ranged data

While np.array can be used to create any array, it is equivalent to hardcoding an array. This won't work when the array has hundreds of values. Instead, NumPy provides an option to create ranged data arrays using np.arange. The function acts very similar to the range function in Python, and will always return a 1-D array.

The code below contains example usages of np.arange.

Python 3.5
arr = np.arange(5)
print(repr(arr))
arr = np.arange(5.1)
print(repr(arr))
arr = np.arange(-1, 4)
print(repr(arr))
arr = np.arange(-1.5, 4, 2)
print(repr(arr))

The output of np.arange is specified as follows:

  • If only a single number, n, is passed in as an argument, np.arange will return an array with all the integers in the range [0, n). Note: the lower end is inclusive while the upper end is exclusive.
  • For two arguments, m and n, np.arange will return an array with all the integers in the range [m, n).
  • For three arguments, m, n, and s, np.arange will return an array with the integers in the range [m, n) using a step size of s.
  • Like np.array, np.arange performs upcasting. It also has the dtype keyword argument to manually cast the array.

To specify the number of elements in the returned array, rather ...