NumPy - Array From Numerical Ranges

Array From Numerical Ranges in NumPy

Creating arrays from numerical ranges in NumPy refers to generating arrays that contain sequences of numbers within a specified range. NumPy provides several functions to create such arrays, they are as follows −

  • Using numpy.arange() Function
  • Using numpy.linspace() Function
  • Using numpy.logspace() Function
  • Using numpy.meshgrid() Function

Using numpy.arange() Function

The numpy.arange() function creates an array by generating a sequence of numbers based on specified start, stop, and step values. It is similar to Python’s built-in range() function but returns a NumPy array. Following is the syntax −

numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)

Where,

  • start (optional) − The starting value of the interval. Default is 0.
  • stop − The end value of the interval (not included).
  • step (optional) − The spacing between values. Default is 1.
  • dtype (optional) − The desired data type for the array. If not given, NumPy interprets the data type from the input values.

Example: Basic Usage

In the following example, we are using the numpy.arange() function to generate an array starting from 0 up to (but not including) 10 −

import numpy as np

# Create an array from 0 to 9
arr = np.arange(10)
print("Array using arange():", arr)

Following is the output obtained −

Array using arange(): [0 1 2 3 4 5 6 7 8 9]

Example: Specifying Start, Stop, and Step

In here, we are generating an array starting from 1, up to (but not including) 10, with a step of 2 using the numpy.arange() function −

import numpy as np

# Create an array from 1 to 9 with a step of 2
arr = np.arange(1, 10, 2)
print("Array with start, stop, and step:", arr)

This will produce the following result −

Array with start, stop, and step: [1 3 5 7 9]

Using numpy.linspace() Function

The numpy.linspace() function generates an array with evenly spaced values over a specified interval. It is useful when you need a specific number of points between two values.

This function is similar to the arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified. Following is the syntax −

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

Where,

  • start − The starting value of the interval.
  • stop − The end value of the interval.
  • num (optional) − The number of evenly spaced samples to generate. Default is 50.
  • endpoint (optional) − If True, stop is the last sample. If False, it is not included. Default is True.
  • retstep (optional) − If True, returns (samples, step), where step is the spacing between samples. Default is False.
  • dtype (optional) − The desired data type for the array. If not given, NumPy interprets the data type from the input values.
  • axis (optional) − The axis in the result along which the samples are stored. Default is 0.

Example: Basic Usage

In this example, we are using the numpy.linspace() function to generate an array of 10 evenly spaced values from 0 to 1 (inclusive by default) −

import numpy as np

# Create an array of 10 evenly spaced values from 0 to 1
arr = np.linspace(0, 1, 10)
print("Array using linspace():", arr)

Following is the output of the above code −

Array using linspace(): [0.         0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
 0.66666667 0.77777778 0.88888889 1.        ]

Example: Excluding Endpoint

In here, we are generating an array of 10 evenly spaced values from 0 to just below 1, excluding the endpoint using the numpy.linspace() function −

import numpy as np

# Create an array 
arr = np.linspace(0, 1, 10, endpoint=False)
print("Array with endpoint=False:", arr)

The output obtained is as shown below −

Array with endpoint=False: [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

Example: Returning Step Size

Now, we are generating an array of 10 evenly spaced values from 0 to 1 (inclusive by default) and also returns the step size −

import numpy as np

# Create an array 
arr, step = np.linspace(0, 1, 10, retstep=True)
print("Array with step size:", arr)
print("Step size:", step)

After executing the above code, we get the following output −

Array with step size: [0.         0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
 0.66666667 0.77777778 0.88888889 1.        ]
Step size: 0.1111111111111111

Using numpy.logspace() Function

The numpy.logspace() function generates an array with values that are evenly spaced on a log scale. This is useful for generating values that span several orders of magnitude. Following is the syntax −

numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)

Where,

  • start − The starting value of the sequence (as a power of base).
  • stop − The end value of the sequence (as a power of base).
  • num (optional) − The number of samples to generate. Default is 50.
  • endpoint (optional) − If True, stop is the last sample. If False, it is not included. Default is True.
  • base (optional) − The base of the log space. Default is 10.0.
  • dtype (optional) − The desired data type for the array. If not given, NumPy interprets the data type from the input values.
  • axis (optional) − The axis in the result along which the samples are stored. Default is 0.

Example

In the example below, we are using the numpy.logspace() function to generate an array of 10 values evenly spaced on a logarithmic scale from 21 to 210 with base 2 −

import numpy as np

# Create an array 
arr = np.logspace(1, 10, 10, base=2)
print("Array with base 2:", arr)

We get the output as shown below −

Array with base 2: [   2.    4.    8.   16.   32.   64.  128.  256.  512. 1024.]

Using numpy.meshgrid() Function

The numpy.meshgrid() function generates coordinate matrices from coordinate vectors. This is useful for creating grids of points for evaluating functions over a 2D or 3D space. Following is the syntax −

numpy.meshgrid(*xi, copy=True, sparse=False, indexing='xy')

Where,

  • *xi − 1-D arrays representing the coordinates of a grid.
  • copy (optional) − If True, a copy of the input arrays is made. Default is True.
  • sparse (optional) − If True, a sparse grid is returned to save memory. Default is False.
  • indexing (optional) − Specifies the Cartesian (‘xy’, default) or matrix (‘ij’) indexing convention.

Example: Creating a 2D Grid

In the example below, we are using the numpy.meshgrid() function to generate coordinate matrices “X” and “Y” from 1D arrays “x” and “y”, where X represents the x-coordinates and Y represents the y-coordinates of a 2D grid −

import numpy as np

# Create 1D arrays for x and y coordinates
x = np.arange(1, 4)
y = np.arange(1, 3)

# Generate coordinate matrices
X, Y = np.meshgrid(x, y)

print("X grid:")
print(X)
print("Y grid:")
print(Y)

Following is the output obtained −

X grid:
[[1 2 3]
 [1 2 3]]
Y grid:
[[1 1 1]
 [2 2 2]]

Example: Creating a 3D Grid

Now, we are generateing coordinate matrices X, Y, and Z from 1D arrays x, y, and z for a 3D grid using matrix indexing (‘ij’) −

import numpy as np

# Create 1D arrays for x, y, and z coordinates
x = np.arange(1, 4)
y = np.arange(1, 3)
z = np.arange(1, 3)

# Generate coordinate matrices
X, Y, Z = np.meshgrid(x, y, z, indexing='ij')

print("X grid:")
print(X)
print("Y grid:")
print(Y)
print("Z grid:")
print(Z)

After executing the above code, we get the following output −

X grid:
[[[1 1]
  [1 1]]

 [[2 2]
  [2 2]]

 [[3 3]
  [3 3]]]
Y grid:
[[[1 1]
  [2 2]]

 [[1 1]
  [2 2]]

 [[1 1]
  [2 2]]]
Z grid:
[[[1 2]
  [1 2]]

 [[1 2]
  [1 2]]

 [[1 2]
  [1 2]]]
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team