Course Content
Ultimate NumPy
3. Commonly used NumPy Functions
Ultimate NumPy
Creation Functions for 1D Arrays
Besides basic array creation via explicitly specifying the elements of the array numpy
also allows automatic array creation using special creation functions. Here are two of the most common creation functions which create exclusively 1D arrays:
arange()
;linspace()
.
arange()
numpy.arange()
function is similar to the Python built-in range()
function, however, it returns an ndarray
. Basically, it creates an array with evenly spaced elements within a certain given interval.
Start, Stop, Step
Its three most important parameters are start
(0
by default), stop
(no default value) and step
(1
by default). The first array element is equal to start
, and each next one is equal to the previous element + step
until the stop
value is reached (stop
is not included in the array) or exceeded.
Let’s see this function in action:
For array_1
we only set the stop
parameter to 11
, for array_2
we set both the start
to 1
and stop
to 11
, and for array_3
we specified all of the three parameters with step=2
.
As you can see with array_4
, we can also specify the data type of the elements.
linspace()
While arange()
can work with real numbers, it is often better to use numpy.linspace()
for this purpose. With linspace()
instead of the step
parameter there is num
parameter used to specify the number of samples (numbers) within a given interval (50 by default).
Let’s see how we can use this function:
As you can see, everything is quite simple here.
Endpoint
Let’s rather focus on the endpoint
boolean parameter. Its default value is True
meaning that the stop
value is inclusive. Setting it to False
excludes this value thus making the step lower and shifting the interval (have a closer look at array_1
and array_3
).
Note
You can always explore more about these functions in their documentation: arange, linspace.
Task
- Use the
arange()
function to createeven_numbers
array. - Specify the arguments in the correct order to create an array of even numbers from
2
to21
exclusive. - Use the appropriate function to create
samples
array which allows specifying the number of values within an interval. - Specify the first three arguments in the correct order to create an array of
10
equally spaced numbers between5
and6
. - Set the rightmost keyword argument, so that
6
is not included in thesamples
array.
Everything was clear?