Random array of integers using NumPy in Python
In this tutorial, we will learn how to generate a random array of integer values in Python using NumPy.
We have covered these things:
- Generate array of random numbers.
- Multidimensional random array generation.
- Random array with some specific given elements.
In order to generate an array with random integer elements in it, we need to generate random integers and then put the integer values in that array.
We can easily generate random numbers with the following piece code:
from numpy import random print(random.randint(10))
It will give you an output of a random number, each time you run the program. The range will be from 0 to 9.
Why 9?
Let’s understand this as well. random.randint(n)
Here n
is an integer value and it will return a random integer value from 0 to (n-1).
Generate an array of random numbers in Python
If we think in a simple way, the best possible way is to create an empty array and then using for loop
, we can assign random numbers to the array elements.
It’s a good practice to avoid for loop as much as possible to make our program more optimized.
Thank God, in the above-mentioned built-in function, there is an optional parameter that will help us to generate multiple random numbers at once. It will also return the random numbers as an array object. Let’s try this with a simple program.
from numpy import random print(random.randint(10, size=(7)))
Whatever value we will provide in the size parameter, will generate a random array of that specific size.
Sample output:
[4 8 0 7 3 5 0]
Each time you run the program, it will output an array with 7 random numbers ranging from 0 to 9.
Multidimensional array of random numbers
We can use the size parameter to generate 2d,3d or more multidimensional arrays.
from numpy import random print(random.randint(10, size=(2,7)))
Output:
[[3 5 5 8 3 6 8] [4 8 5 7 6 2 2]]
Another example:
from numpy import random print(random.randint(10, size=(2,3,4)))
Output:
[[[0 7 3 1] [3 9 0 9] [1 2 2 2]] [[4 1 4 7] [1 7 5 4] [2 2 0 6]]]
Generate a random array with specific numbers only
from numpy import random print(random.choice([10,12,4,6], size=(10)))
Sample output:
[10 10 12 6 12 10 12 6 4 12]
As you can see it will only return an array from the specific given elements randomly.
Leave a Reply