How to generate random integers between 0 and 9(inclusive) in NumPy Python?

randint() function is used to generate random integers in NumPy. This function does not include the upper bound of the interval, so instead of writing 9 in the upper bound, you have to write 10. Also, randint() is found in NumPy's random module.

import numpy as np
arr = np.random.randint(0, 10)
print(arr)

Output

8

When you do not specify the size parameter, then only a single random integer is generated. If you want to generate 2 dimensional NumPy array, then pass a tuple of integers to the size parameter.

import numpy as np
arr = np.random.randint(0, 10, size=(4, 3))
print(arr)

Output

[[6 8 9]
 [1 5 4]
 [5 8 8]
 [2 7 2]]

The above code will generate a 2 dimensional NumPy array having 12 elements.

Recommended Posts