Create Array with Random Values – NumPy

Create NumPy Array with Random Values

To create a numpy array of specific shape with random values, use numpy.random.rand() with the shape of the array passed as argument.

In this tutorial, we will learn how to create a numpy array with random values using examples.

Syntax

The syntax of rand() function is:

numpy.random.rand(d0,d1,d2,...,dN)

where d0, d1, d2,.. are the sizes in each dimension of the array.

For example, numpy.random.rand(2,4) mean a 2-Dimensional Array of shape 2x4. And numpy.random.rand(51,4,8,3) mean a 4-Dimensional Array of shape 51x4x8x3.

The function returns a numpy array with the specified shape filled with random float values between 0 and 1.

Examples

1. Create 1D array with random values

To create a 1-D numpy array with random values, pass the length of the array to the rand() function.

In this example, we will create 1-D numpy array of length 7 with random values for the elements.

Python Program

import numpy as np

# Numpy array with random values
a = np.random.rand(7)

print(a)
Run Code Copy

Output

[0.92344589 0.93677101 0.73481988 0.10671958 0.88039252 0.19313463
 0.50797275]

2. Create 2D array with random values

To create a 2-dimensional numpy array with random values, pass the required lengths of the array along the two dimensions to the rand() function.

In this example, we will create 2-dimensional numpy array of length 2 in dimension-0, and length 4 in dimension-1 with random values.

Python Program

import numpy as np

# Numpy array with random values
a = np.random.rand(2,4)

print(a)
Run Code Copy

Output

[[0.20499018 0.07289246 0.94701953 0.42017761]
 [0.66925148 0.53029125 0.70718627 0.36887072]]

3. Create 3D array with random values

To create a 3-dimensional numpy array with random values, pass the lengths along three dimensions of the array to the rand() function.

In this example, we will create 3-dimensional numpy array of lengths 4, 2, 3 along the three dimensions with random values.

Python Program

import numpy as np

# Numpy array with random values
a = np.random.rand(4,2,3)

print(a)
Run Code Copy

Output

[[[0.78239285 0.77998473 0.29194015]
  [0.23218306 0.0828319  0.55339258]]

 [[0.20713848 0.67568804 0.5708645 ]
  [0.28212859 0.11966318 0.39348758]]

 [[0.63716278 0.33080523 0.33078874]
  [0.11114847 0.75312359 0.17301032]]

 [[0.88010661 0.03097883 0.38684319]
  [0.97854578 0.87874426 0.71835589]]]

Summary

In this tutorial of Python Examples, we have created numpy arrays of different dimensions with random values using numpy.random.rand() function.

Related Tutorials

Code copied to clipboard successfully 👍