NumPy: Create an Array from Numerical Ranges

In Numpy, we can create array from numerical ranges by using the following NumPy functions.

numpy.arrange:

This function returns an ndarray. It creates an ndarray object containing evenly spaced values within a given range of interval.

Syntax:

numpy.arange(start, stop, step, dtype)

Parameters:

  1. start: The starting of an array. If it is omitted then it defaults to 0.
  2. stop: This is the ending of an array. This value is excluded.
  3. step:  It is used for spacing between values default is 1.
  4. dtype: It is used to describe the data type of the numpy array items.

Example:

import numpy as np  
a= np.arange(1,9,2,float)  
print(a)  

Output:

[1. 3. 5. 7.]

numpy.linspace:

Similar as arrange() function. In this function, only returns evenly separated values over a specified interval instead of step size.

Syntax:

numpy.linspace(start, stop, num, endpoint, retstep, dtype)  

Parameters:

  1. start: It is used to represent starting values of sequence.
  2. stop: It is used to represents the stopping value of the sequence.
  3. num: It represents the amount of evenly spaced samples over the interval to be generated. Its default is 50.
  4. endpoint: If the stop value is included it is true else false, if not included.
  5. retstep: It return samples and step between the consecutive numbers, if it is true.
  6. dtype: It is used to represent the data type of ndarray.

Example:

import numpy as np

a=np.linspace(10,100,10,endpoint=True)
b=np.linspace(10,100,10, retstep=True)

print(a)
print(b)

Output:

[ 10.  20.  30.  40.  50.  60.  70.  80.  90. 100.]
(array([ 10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90., 100.]), 10.0)

numpy.logspace:

 This function returns an ndarray, which creates an array by using the numbers that are evenly separated on a log scale.

Syntax:

numpy.logspace(start, stop, num, endpoint, base, dtype)  

Parameters:

  1. start: It is used to represents the starting value of sequence in the base.
  2. stop: It is used to represents the stopping value of sequence  in the base
  3. num: It is used to give the number of values between the range.Its default is 50.
  4. endpoint: If it is True then stop is the last value in the range.
  5. base: It represent the base of log space, Its default is 10.
  6. dtype: It represents the data type of the ndarray elements.

Example:

import numpy as np 
a=np.logspace(1,5,num=5, base=2) 
print(a)

Output: [ 2. 4. 8. 16. 32.]

Thu, 08/05/2021 - 20:31

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.