Table of Contents
ToggleWe can create a NumPy array using various functions 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 −
numpy.array() Functionnumpy.zeros() Functionnumpy.ones() Functionnumpy.arange() Functionnumpy.linspace() Functionnumpy.random.rand() Functionnumpy.empty() Functionnumpy.full() FunctionUnlike Python lists, NumPy arrays support element-wise operations and are more memory-efficient, making them useful for mathematical computations.
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)
In the following example, we are creating a 1-dimensional NumPy array from a list of integers using the numpy.array() function −
# Open Compiler
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)
Output:
Following is the output obtained −
1D Array: [1 2 3 4 5]
In here, we are creating a 2-dimensional NumPy array from a list of lists using the numpy.array() function −
# Open Compiler
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)
Output:
This will produce the following result −
2D Array:
[[1 2 3]
[4 5 6]]
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')
In this example, we are creating a NumPy array with 5 elements, all initialized to zero using the numpy.zeros() function −
# Open Compiler import numpy as np # Creating an array of zeros arr = np.zeros(5) print(arr)
Output:
Following is the output of the above code −
[0. 0. 0. 0. 0.]
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.
float64” if not provided.Following is the syntax −
numpy.ones(shape, dtype=None, order='C')
In the example below, we are creating a 1 dimensional NumPy array with 3 elements, all initialized to one using the numpy.ones() function −
# Open Compiler import numpy as np # Creating an array of ones arr = np.ones(3) print(arr)
Output:
After executing the above code, we get the following output −
[1. 1. 1.]
In here, we create a 2 dimensional NumPy array with 4 rows and 3 columns, filled with ones, using the np.ones() function −
# Open Compiler import numpy as np # Creating 2D array of ones array_2d = np.ones((4, 3)) print(array_2d)
Output:
The result produced is as follows −
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
Now, we are creating a 2-dimensional NumPy array with 4 rows and 3 columns, filled with ones, using the np.ones() function with Fortran-style (column-major) order −
# Open Compiler import numpy as np # Creating Fortran-ordered array of ones array_F = np.ones((4, 3), order='F') print(array_F)
Output:
We get the output as shown below −
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
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.
Following is the syntax −
numpy.arange([start,] stop[, step,] dtype=None, *, like=None)
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 −
# Open Compiler
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)
Output:
Following is the output obtained −
array1: [0 1 2 3 4 5 6 7 8 9]
array2: [1 3 5 7 9]
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.
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 −
# Open Compiler
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)
Output:
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
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)
In the following example, we are using numpy.random.rand() function to generate arrays of random floats with different dimensions −
# Open Compiler
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)
Output:
Following is the output of the above code (values will vary due to randomness) −
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 ]]]
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.
In this example, we are using numpy.empty() function to create a 2-dimensional array (empty_array) with 2 rows and 3 columns −
# Open Compiler import numpy as np empty_array = np.empty((2, 3)) print(empty_array)
Output:
The output obtained is as shown below (values will vary due to uninitialized memory) −
[[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 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')
In the following example, we are using the numpy.full() function to create a 2-dimensional array with dimensions 2×3, filled entirely with the value 5 −
# Open Compiler import numpy as np array1 = np.full((2, 3), 5) print(array1)
Output:
After executing the above code, we get the following output −
[[5 5 5]
[5 5 5]]
In the NumPy module, there are various ways to create NumPy arrays that include 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 −
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 |
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 |
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 |
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 |
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 |
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 |
Key Takeaway: Learn to create NumPy arrays efficiently at Vista Academy!
