NumPy Selective Random
Submitted by moazkhan on Monday, June 22, 2020 - 10:00.
In this tutorial you will learn:
- What is selective random?
- NumPy choice() function
- How to use choice() function
Selective Random
Selective random is a technique for random sampling in which the data set from which the sample has to be selected is dependent on the specific pre-defined values. For example if we want to randomly select the professor of certain university who can proficiently carry out a specific research, here we would provide specific data set of those professors (which meet the criteria) to the random function, which will then choose the professor(s) randomly.
Choice() Function
To implement random sampling on a given data set, the NumPy provides a function “choice()” which takes in a data set in the form of an array as a parameter, randomly select one of the element from the data set and returns it. The function was added in NumPy 1.7.0. The choice() function can take in 4 parameters, out of which one is mandatory and three are optional. The first parameter is a 1D array from which we want to choose the random element, second argument is the size of output array, third argument determines whether the sample being returned by the function will be with replacement or without replacement. The fourth argument, is a 1D array which is of the exact size of the first parameter and it assigns the probability of selection to each element. In this example we will select a number randomly from the given data set of [2,4,6,8].- print(' ** NumPy Selective Random **')
- from numpy import random as r
- #defining input
- a=[2,4,6,8]
- print('1D input array:',a)
- #using the choice() function
- res = r.choice(a)
- #printing result
- print('The selected number is', res)
- from numpy import random as r
- #defining input
- a=['a','b','c','d','e']
- print('1D input array:',a)
- #using the choice() function
- res = r.choice(a)
- #printing result
- print('The selected number is', res)
- from numpy import random as r
- #defining input
- a=[2,4,6,8]
- print('1D input array:',a)
- #using choice() function along with the output array size as (2,4)
- res = r.choice(a,size=(2,4))
- #printing result
- print('The 2D output array is:', res)
Add new comment
- 65 views