
- 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 Creation Routines
Creating NumPy Array
We can create a NumPy array using various function provided by the Python NumPy library. This package provides a multidimensional array object and various other required objects, routines, for efficient functionality. Following are the functions using which we can create a NumPy array −
- Using numpy.array() Function
- Using numpy.zeros() Function
- Using numpy.ones() Function
- Using numpy.arange() Function
- Using numpy.linspace() Function
- Using numpy.random.rand() Function
- Using numpy.empty() Function
- Using numpy.full() Function
Unlike Python lists, NumPy arrays support element-wise operations and are more memory-efficient, making them useful for mathematical computations.
Using numpy.array() Function
We can use the numpy.array() function to create an array by passing a Python list or tuple as an argument to the function.
This function converts input data (like lists, tuples, etc.) into an ndarray (NumPy array). Following is the syntax −
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0, like=None)
Example: Creating a 1D NumPy Array
In the following example, we are creating a 1-dimensional NumPy array from a list of integers using the numpy.array() function −
import numpy as np # Creating a 1D array from a list my_list = [1, 2, 3, 4, 5] my_array = np.array(my_list) print("1D Array:", my_array)
Following is the output obtained −
1D Array: [1 2 3 4 5]
Example: Creating a 2D NumPy Array
In here, we are creating a 2-dimensional NumPy array from a list of lists using the numpy.array() function −
import numpy as np # Creating a 2D array from a list of lists arr = np.array([[1, 2, 3], [4, 5, 6]]) print("2D Array:\n", arr)
This will produce the following result −
2D Array: [[1 2 3] [4 5 6]]
Using numpy.zeros() Function
We can also use the numpy.zeros() function for creating an array by specifying the desired shape of the array as a tuple or an integer.
This function creates a NumPy array filled with zeros. It accepts the shape of the array as an argument and optionally the data type (dtype). By default, the data type is float64. Following is the syntax −
numpy.zeros(shape, dtype=float, order='C')
Example
In this example, we are creating a NumPy array with 5 elements, all initialized to zero using the numpy.zeros() function −
import numpy as np # Creating an array of zeros arr = np.zeros(5) print(arr)
Following is the output of the above code −
[0. 0. 0. 0. 0.]
Using numpy.ones() Function
On the other hand, the numpy.ones() function creates an array where all elements are set to 1. It accepts three main parameters: shape, dtype, and order.
- The shape parameter, which can be an integer or a tuple of integers, defines the dimensions of the array.
- The dtype parameter specifies the desired data type of the array elements, defaulting to "float64" if not provided.
- The order parameter determines the memory layout of the array, either row-major (C-style) or column-major (Fortran-style), with 'C' being the default.
Following is the syntax −
numpy.ones(shape, dtype=None, order='C')
Example: Creating 1D array of ones
In the example below, we are creating a 1 dimensional NumPy array with 3 elements, all initialized to one using the numpy.ones() function −
import numpy as np # Creating an array of ones arr = np.ones(3) print(arr)
After executing the above code, we get the following output −
[1. 1. 1.]
Example: Creating 2D array of ones
In here, we create a 2 dimensional NumPy array with 2 rows and 3 columns, filled with ones, using the np.ones() function −
import numpy as np # Creating 2D array of ones array_2d = np.ones((4, 3)) print(array_2d)
The result produced is as follows −
[[1. 1. 1.] [1. 1. 1.] [1. 1. 1.] [1. 1. 1.]]
Example: Creating a Fortran-ordered array of ones
Now, we are creating a 2-dimensional NumPy array with 2 rows and 3 columns, filled with ones, using the np.ones() function with Fortran-style (column-major) order −
import numpy as np # Creating Fortran-ordered array of ones array_F = np.ones((4, 3), order='F') print(array_F)
We get the output as shown below −
[[1. 1. 1.][1. 1. 1.][1. 1. 1.][1. 1. 1.]]
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.
This function creates an array of evenly spaced values within a given interval. It allows specifying the start, stop, and step size, and returns a NumPy array.
start − The starting value of the sequence. If not specified, it defaults to 0.
stop − The end value of the sequence. This value is exclusive, meaning it is not included in the sequence.
step − The step or interval between each pair of consecutive values in the sequence. If not specified, it defaults to 1.
Following is the syntax −
numpy.arange([start,] stop[, step,] dtype=None, *, like=None)
Example
In the following example, we first create a NumPy array "array1" from 0 to 9. Then, we create another array "array2" with values starting from 1 up to (but not including) 10, with a step of 2 using the np.arange() function −
import numpy as np # Providing just the stop value array1 = np.arange(10) print("array1:", array1) # Providing start, stop and step value array2 = np.arange(1, 10, 2) print("array2:",array2)
Following is the output obtained −
array1: [0 1 2 3 4 5 6 7 8 9] array2: [1 3 5 7 9]
Using numpy.linspace() Function
We can even use the numpy.linspace() function to create an array by specifying the start, stop, and the number of elements we want.
The array created by this function consists of evenly spaced values over a specified interval. The function takes parameters for start, stop, and the number of elements, and generates values that are evenly distributed between the start and stop values, inclusive. Following is the syntax −
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
The numpy.linspace() function is particularly useful when you need a set number of points between two endpoints for plotting or numerical computations.
Example
In the example below, we are using numpy.linspace() function to create three arrays (array1, array2, and array3) with specified ranges and configurations.
The "array1" is created with 10 evenly spaced values from 0 to 5, inclusive. The "array2 consists of 5 values ranging from 1 to just under 2, excluding the endpoint. The "array3" is created with 5 values from 0 to 10, and returns both the array and the step size between consecutive values −
import numpy as np # Creating an array of 10 evenly spaced values from 0 to 5 array1 = np.linspace(0, 5, num=10) print("array1:",array1) # Creating an array with 5 values from 1 to 2, excluding the endpoint array2 = np.linspace(1, 2, num=5, endpoint=False) print("array2:",array2) # Creating an array and returning the step value array3, step = np.linspace(0, 10, num=5, retstep=True) print("array3:",array3) print("Step size:", step)
This will produce the following result −
array1: [0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.33333333 3.88888889 4.44444444 5. ] array2: [1. 1.2 1.4 1.6 1.8] array3: [ 0. 2.5 5. 7.5 10. ] Step size: 2.5
Using random.rand() Function
Alternatively, we can use the numpy.random.rand() function for creating an array by specifying the dimensions of the array as parameters.
This function is used to create an array of specified shape filled with random values sampled from a uniform distribution over [0, 1).
It accepts parameters for the dimensions of the array (like numpy.random.rand(rows, columns)), and generates an array of the specified shape with random values between 0 and 1. If no argument is provided, it returns a single random float value. Following is the syntax −
numpy.random.rand(d0, d1, ..., dn)
Example
In the following example, we are using numpy.random.rand() function to generate arrays of random floats with different dimensions −
import numpy as np # Generating a single random float random_float = np.random.rand() print("random_float:",random_float) # Generating a 1D array of random floats array_1d = np.random.rand(5) print("array_1d:",array_1d) # Generating a 2D array of random floats array_2d = np.random.rand(2, 3) print("array_2d:",array_2d) # Generating a 3D array of random floats array_3d = np.random.rand(2, 3, 4) print("array_3d:",array_3d)
Following is the output of the above code −
random_float: 0.5030496450079744 array_1d: [0.19476581 0.54430648 0.64571106 0.27443774 0.71874319] array_2d: [[0.91141582 0.58847504 0.37284854] [0.0715398 0.21305363 0.766954 ]] array_3d: [[[0.7295106 0.1582053 0.91376381 0.14099229] [0.6876814 0.19351871 0.18056163 0.61370308] [0.42382443 0.6665121 0.42322218 0.11707395]] [[0.60883975 0.01724199 0.95753734 0.17805716] [0.47770594 0.55840874 0.7375783 0.50512301] [0.73730351 0.85900855 0.16472072 0.2338285 ]]]
Using numpy.empty() Function
We can create a NumPy array using the numpy.empty() function by specifying the shape of the array as parameters.
This function initializes an array without initializing its elements; the content of the array is arbitrary and may vary. It is useful when you need an array of a specific size and data type, but you intend to fill it later with data. Following is the syntax −
numpy.empty(shape, dtype=float, order='C')
Unlike numpy.zeros() function and numpy.ones() function, which initialize array elements to zero and one respectively, the numpy.empty() function does not initialize the elements. Instead, it allocates the memory required for the array without setting any values.
Example
In this example, we are using numpy.empty() function to create a 2-dimensional array (empty_array) with 2 rows and 3 columns −
import numpy as np empty_array = np.empty((2, 3)) print(empty_array)
The output obtained is as shown below −
[[1.13750619e-313 0.00000000e+000 0.00000000e+000] [0.00000000e+000 0.00000000e+000 0.00000000e+000]]
Unlike numpy.zeros(), this function initializes the array with uninitialized values, which could be any random data left in memory, making it suitable for cases where immediate initialization is not required.
Using numpy.full() Function
Using the numpy.full() function, we can create an array with a desired shape and set all the elements in it to a specific value. Following is the syntax −
numpy.full(shape, fill_value, dtype=None, order='C')
Example
In the following example, we are using the numpy.full() function to create a 2-dimensional array with dimensions 2x3, filled entirely with the value 5 −
import numpy as np array1 = np.full((2, 3), 5) print(array1)
After executing the above code, we get the following output −
[[5 5 5] [5 5 5]]
Functions Used for Creation of NumPy Arrays
In the NumPy module, there are various ways to create NumPy arrays that includes, basic creation methods, creation by reshaping and modifying data, creation using sequences, and creation using random functions. Following are the different functions used to create NumPy arrays −
Basic Array Creation
Following are the basic functions for creation of array −
Sr.No. | Functions & Description |
---|---|
1 |
array()
used to create a numpy array |
2 |
asarray()
Convert the input to an array |
3 |
asanyarray()
Convert the input to an ndarray, but pass ndarray subclasses through |
4 |
copy()
Return an array copy of the given object |
Array Creation with Specific Shapes and Data
Following are the functions used to create an array with specified shapes and data −
Sr.No. | Functions & Description |
---|---|
1 |
zeros()
Return a new array of given shape and type, filled with zeros |
2 |
ones()
Return a new array of given shape and type, filled with ones |
3 |
empty()
Return a new array of given shape and type, without initializing entries |
4 |
full()
Return a new array of given shape and type, filled with fill_value |
Array Creation with Sequences
Following are the functions used to create an array with sequences −
Sr.No. | Functions & Description |
---|---|
1 |
arange()
Return evenly spaced values within a given interval |
2 |
linspace()
Return evenly spaced numbers over a specified interval. |
3 |
logspace()
Return numbers spaced evenly on a log scale. |
Special Arrays
Following are the special functions to create an array −
Sr.No. | Functions & Description |
---|---|
1 |
eye()
Return a 2-D array with ones on the diagonal and zeros in all other positions |
2 |
identity()
Return the identity array. |
3 |
diag()
Extract a diagonal or construct a diagonal array |
4 |
fromfunction()
Construct an array by executing a function over each coordinate |
5 |
fromfile()
Construct an array from data in a text or binary file |
Random Arrays
Following are the random functions to create an array −
Sr.No. | Functions & Description |
---|---|
1 |
random.rand()
Random values in a given shape |
2 |
random.randn()
Return a sample from the standard normal distribution |
3 |
random.randint()
Return random integers from low (inclusive) to high (exclusive) |
4 |
random.random()
Return random floats in the half-open interval [0.0, 1.0) |
5 |
random.choice()
Generates a random sample from a given 1-D array |
Structured Array
Following are the structured functions used to create an array −
Sr.No. | Functions & Description |
---|---|
1 |
zeros_like()
Return an array of zeros with the same shape and type as a given array |
2 |
ones_like()
Return an array of ones with the same shape and type as a given array. |
3 |
empty_like()
Return a new array with the same shape and type as a given array |
4 |
full_like()
Return a full array with the same shape and type as a given array |