[PYTHON] Pseudo-random number generation and random sampling

Generate random numbers with standard modules

Python has a random module as a standard library, which can generate random numbers with various distributions. It has the following main features.

Random number generation example

In NumPy's Random Sample Function (http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random_sample.html#numpy.random.random_sample), it's a floating point number or an integer (http) You can generate random numbers at //docs.scipy.org/doc/numpy/reference/generated/numpy.random.random_integers.html#numpy.random.random_integers).

np.random.random_sample((5,))
#=> array([ 0.80055457,  0.19615444,  0.50532311,  0.48243283,  0.56227889])

np.random.random_sample((5,2))
#=>
# array([[ 0.59495428,  0.56194628],
#        [ 0.93675326,  0.88873404],
#        [ 0.98967746,  0.2319963 ],
#        [ 0.20625308,  0.76956028],
#        [ 0.7870824 ,  0.30181687]])

Random sorting of data frames

Random permutation of data frames is possible by using permutation I will.

df = pd.DataFrame(np.arange(10*4).reshape(10,4))
sampler = np.random.permutation(5)
#=> array([0, 2, 1, 3, 4])

df.take(sampler)
#=>
#     0   1   2   3
# 0   0   1   2   3
# 2   8   9  10  11
# 1   4   5   6   7
# 3  12  13  14  15
#4  16  17  18  19

np.random.permutation(len(df))
#=> array([6, 7, 8, 3, 9, 4, 2, 1, 0, 5])

Pull playing cards

Consider a cord that draws 10 cards from a pile of 52 playing cards. You can shuffle using random.shuffle, so you can subtract any number from here.

#Prepare a pile of playing cards
deck = list(
    itertools.product(list(range(1, 14)),
                      ['spade', 'heart', 'Diamond', 'club']))

random.shuffle(deck) #Shuffle the deck

print("Card drawn:")
for i in range(10): #Draw 10 cards
    print(deck[i][1] + "of" + str(deck[i][0]))

#=>Card drawn:
#Diamond 6
#Club 3
#10 of hearts
#Diamond 12
#8 of spades
#Club 13
#Diamond 13
#5 of spades
#12 of hearts
#Diamond 7

Since there are only 52 playing cards, random.shuffle (53) will result in IndexError.

Recommended Posts

Pseudo-random number generation and random sampling
High-dimensional random number vector generation ~ Latin Hypercube Sampling / Latin hypercube sampling ~
[python] Random number generation memorandum
Non-overlapping integer random number generation (0-N-1)
Random number generation summary by Numpy
#Random string generation
Derivation of multivariate t distribution and implementation of random number generation by python
[Note] Random number creation?
Random string generation (Python)
Numpy random module random number generator
Decision tree and random forest
A1 notation and 26-ary number
Random number seed fixed in TensorFlow and Numpy A little different