NumPy Basics
Perform basic operations to create and modify NumPy arrays.
We'll cover the following...
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
.
Press + to interact
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 thedtype
keyword
Access this course and 1400+ top-rated courses and projects.