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]]