Related Tags

numpy
random
communitycreator

# How to generate a random number or array from an array in NumPy

Onyejiaku Theophilus Chidalu

To generate a random numberA random number is a number that can not be predicted logically. From this simple definition, it is easy to understand that a random number does not necessarily mean a different number every time. or a random number array from a given array in NumPy, we can use the choice() method.

To generate a random value or a random array from an array in NumPy, we must import the random module.

Let’s have a look at the syntax and code example below to see how we can generate a random array from the given array:

### Syntax

The syntax to generate a random array from the given array is:

random.choice(array, size)


Where the array parameter contains the array values, while the size parameter specifies the shape of the array.

### Return value

The random.choice(array, size) will return a random array of given size from the array passed as the parameter value.

### Code

In the code below, we will create a random array from the given array using the choice() method. The array will be of the shape specified in the arguments of the function.

# importing the random module from NumPy
from numpy import random

# creating an array
myArray = random.choice([3, 5, 7, 9], size=(3, 5))

# printing the array
print(myArray)
Generate a random array

We use the choice() method to create a 3-by-5 array that contains elements 3, 5, 7, and 9 in random positions.

Let’s have a look at the syntax and code example to see the method to generate a random value from the given array:

### Syntax

The syntax to generate a random number from the given array is:

random.choice(array)


### Return value

The random.choice(array) will return a random value from the array passed as the parameter value.

### Code

from numpy import random

myArray = random.choice([3, 5, 7, 9])

print(myArray)
Generate a random number

By omitting the size parameter from the code used in the first case, we generated just a random number instead of an array from the given array.

RELATED TAGS

numpy
random
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time