How to Create a NumPy Matrix with Random Numbers


You can use the following methods to create a NumPy matrix with random numbers:

Method 1: Create NumPy Matrix of Random Integers

np.random.randint(low, high, (rows, columns))

Method 2: Create NumPy Matrix of Random Floats

np.random.rand(rows, columns)

The following examples show how to use each method in practice.

Example 1: Create NumPy Matrix of Random Integers

The following code shows how to create a NumPy matrix of random values that ranges from 0 to 20 with a shape of 7 rows and 2 columns:

import numpy as np

#create NumPy matrix of random integers
np.random.randint(0, 20, (7, 2))

array([[ 3,  7],
       [17, 10],
       [ 0, 10],
       [13, 16],
       [ 6, 14],
       [ 8,  7],
       [ 9, 15]])

Notice that each value in the matrix ranges between 0 and 20 and the final shape of the matrix is 7 rows and 2 columns.

Example 2: Create NumPy Matrix of Random Floats

The following code shows how to create a NumPy matrix with random float values between 0 and 1 and a shape of 7 columns and 2 rows:

import numpy as np

#create NumPy matrix of random floats
np.random.rand(7, 2)

array([[0.64987774, 0.60099292],
       [0.13626106, 0.1859029 ],
       [0.77007972, 0.65179164],
       [0.33524707, 0.46201819],
       [0.1683    , 0.72960909],
       [0.76117417, 0.37212974],
       [0.18879731, 0.65723325]])

The result is a NumPy matrix that contains random float values between 0 and 1 with a shape of 7 rows and 2 columns.

Note that you can also use the NumPy round() function to round each float to a certain number of decimal places.

For example, the following code shows how to create a NumPy matrix of random floats each rounded to 2 decimal places:

import numpy as np

#create NumPy matrix of random floats rounded to 2 decimal places
np.round(np.random.rand(5, 2), 2)

array([[0.37, 0.63],
       [0.51, 0.68],
       [0.23, 0.98],
       [0.62, 0.46],
       [0.02, 0.94]])

Note: You can find the complete documentation for the NumPy rand() function here.

Additional Resources

The following tutorials explain how to perform other common conversions in Python:

How to Convert Pandas DataFrame Columns to Strings
How to Convert Timestamp to Datetime in Pandas
How to Convert Datetime to Date in Pandas

Leave a Reply

Your email address will not be published.