
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
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]]]