0718-np.random.choice

PYTHON LEARNING

np.random.choice

The np.random.choice function in NumPy is used to generate a random sample from a given 1-D array. It can be used to select random elements from an array, optionally with or without replacement, and can also be used to create an array of specified shape filled with randomly selected values from the input array.

Here's the basic syntax for np.random.choice:

numpy.random.choice(a, size=None, replace=True, p=None)

Parameters:

  • a: 1-D array-like or int

    • If an array-like, a random sample is generated from its elements.

    • If an int, the random sample is generated as if a were np.arange(a).

  • size: int or tuple of ints, optional

    • The output shape. If the given shape is, for example, (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

  • replace: boolean, optional

    • Whether the sample is with or without replacement. Default is True, meaning samples are drawn with replacement.

  • p: 1-D array-like, optional

    • The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in a.

Examples:

  1. Random selection from an array:

    import numpy as np
    
    array = [1, 2, 3, 4, 5]
    choice = np.random.choice(array)
    print(choice)
  2. Random selection of multiple elements with replacement:

    import numpy as np
    
    array = [1, 2, 3, 4, 5]
    choices = np.random.choice(array, size=3)
    print(choices)
  3. Random selection of multiple elements without replacement:

    import numpy as np
    
    array = [1, 2, 3, 4, 5]
    choices = np.random.choice(array, size=3, replace=False)
    print(choices)
  4. Random selection with specified probabilities:

    import numpy as np
    
    array = [1, 2, 3, 4, 5]
    probabilities = [0.1, 0.2, 0.3, 0.2, 0.2]
    choices = np.random.choice(array, size=3, p=probabilities)
    print(choices)

This function is quite powerful for creating randomized datasets, performing random sampling, and simulating random processes.

Last updated