Random array of integers using NumPy in Python
In this tutorial, we will learn about creating a random array of integers using the NumPy library in Python. In addition, we will learn how to create a NumPy array.NumPy(short for Numerical Python) is an open-source Python library which is used for doing scientific computing and linear algebra with Python.
Create a NumPy Array
A NumPy array is a multidimensional array used to store values of the same datatype. For creating a NumPy array we have to pass a list of element values to a square bracket as a parameter to the np.array() function.
import numpy as np array1d=np.array([1,2,3]) array2d=np.array([[1,2],[3,4]) print(array1d) print(array2d)
[1 2 3 ] [[1 2 ] [3 4]]
We can also create a matrix of random numbers using NumPy. For instance
Random Number Array
- np.random.rand : Generates an array with random numbers that are uniformly distributed between 0 and 1.
- np.random.randn: It generates an array with random numbers that are normally distributed between 0 and 1.
- np.random.randint : Generates an array with random numbers that are uniformly distributed between 0 and given integer.
import numpy as np print(np.random.rand(3,2)) #Uniformly Distributed Values print(np.random.randn(3,2)) #Normally Distributed Values #Uniformly Distributed Integers in a given range print(np.random.randint(2,size=10)) print(np.random.randint(5,size=(2,4)))
[[0.68428242 0.62456548] [0.28595395 0.96066372] [0.63394485 0.94036659]] [[0.29485704 0.84015551] [0.42001253 0.89660667] [0.50442113 0.46681959]] [0 1 1 0 0 0 0 1 1 0] [[3 3 2 3] [2 1 2 0]]
In conclusion, we can say a random array of integers can be generated by using np.random.randint method of the ndarray class of NumPy module.
At last, let me tell you about the advantages of the NumPy array over a Python list. These are some of the advantages:
- It occupies less memory.
- It is fast as compared to lists.
- It is convenient to use.