To generate a 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:
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.
The random.choice(array, size)
will return a random array of given size
from the array
passed as the parameter value.
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)
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:
The syntax to generate a random number from the given array is:
random.choice(array)
The random.choice(array)
will return a random value from the array
passed as the parameter value.
from numpy import random myArray = random.choice([3, 5, 7, 9]) print(myArray)
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
CONTRIBUTOR
View all Courses