How to generate a random numpy array in Python

In this tutorial, let’s learn how to generate a random NumPy array in Python.

NumPy is a Python library used to work with large dimensions of arrays and matrices.

Arrays stores grid values of raw data in rows and columns which may beĀ  accessed using index

Initially, we need to install the NumPy library. Open your command prompt and type the following line.

pip install numpy

Importing the modules

NumPy can be imported as np

import numpy as np

numpy.random.randint

This function returns the integer values from [low, high) and is exclusively used to generate random integers. Here low is inclusive and high is exclusive.

Generating random 1D numpy array in Python

Type 1

np.random.randint(8, size=5)

In the above code, we have passed the size parameter as 5. Therefore, the resultant array will be of size 5.

Here, I have only passed one parameter (8). Hence, it is considered a high parameter that is exclusive So the array elements will not have values greater than or equal to 8.

Output

array([6, 4, 0, 5, 6])

Type 2

np.random.randint(10,15 ,size=10)

Here, the low parameter is 10 and the high parameter is 15. The array elements range from values 10,11,12,13,and 14.

The size of the array is 10.

Output

array([10, 14, 12, 11, 12, 13, 13, 11, 11, 10])

Generating 2D random NumPy array

np.random.randint(5,9 ,size=(2, 4))

In the above code, we have passed two values for the size parameter indicating rows and columns.

array([[8, 7, 6, 6],
       [5, 8, 6, 5]])

Generating random multidimensional NumPy array in Python

np.random.randint(5, size=(3,3, 3,3))

Output

array([[[[4, 1, 3],
         [3, 2, 0],
         [3, 2, 0]],

        [[4, 3, 2],
         [0, 0, 0],
         [0, 0, 2]],

        [[3, 2, 1],
         [4, 3, 2],
         [3, 2, 2]]],


       [[[2, 3, 4],
         [1, 3, 3],
         [0, 1, 2]],

        [[4, 4, 0],
         [1, 3, 2],
         [3, 4, 3]],

        [[1, 3, 3],
         [2, 0, 2],
         [0, 2, 1]]],


       [[[0, 1, 2],
         [2, 4, 2],
         [0, 0, 4]],

        [[2, 3, 4],
         [3, 4, 2],
         [4, 4, 4]],

        [[2, 0, 3],
         [2, 0, 4],
         [1, 1, 0]]]])

 

Leave a Reply

Your email address will not be published. Required fields are marked *