oice — NumPy V1.23 Manual

Skip to main content Back to top Ctrl+K
  • User Guide
  • API reference
  • Building from source
  • Development
  • Release notes
  • Learn
  • NEPs
Choose version
  • GitHub

Section Navigation

  • NumPy’s module structure
  • Array objects
  • Universal functions (ufunc)
  • Routines and objects by topic
    • Constants
    • Array creation routines
    • Array manipulation routines
    • Bit-wise operations
    • String functionality
    • Datetime support functions
    • Data type routines
    • Mathematical functions with automatic domain
    • Floating point error handling
    • Exceptions and Warnings
    • Discrete Fourier Transform
    • Functional programming
    • Input and output
    • Indexing routines
    • Linear algebra
    • Logic functions
    • Masked array operations
    • Mathematical functions
    • Miscellaneous routines
    • Polynomials
    • Random sampling
      • Random Generator
      • Legacy Generator (RandomState)
        • numpy.random.RandomState.get_state
        • numpy.random.RandomState.set_state
        • numpy.random.RandomState.seed
        • numpy.random.RandomState.rand
        • numpy.random.RandomState.randn
        • numpy.random.RandomState.randint
        • numpy.random.RandomState.random_integers
        • numpy.random.RandomState.random_sample
        • numpy.random.RandomState.choice
        • numpy.random.RandomState.bytes
        • numpy.random.RandomState.shuffle
        • numpy.random.RandomState.permutation
        • numpy.random.RandomState.beta
        • numpy.random.RandomState.binomial
        • numpy.random.RandomState.chisquare
        • numpy.random.RandomState.dirichlet
        • numpy.random.RandomState.exponential
        • numpy.random.RandomState.f
        • numpy.random.RandomState.gamma
        • numpy.random.RandomState.geometric
        • numpy.random.RandomState.gumbel
        • numpy.random.RandomState.hypergeometric
        • numpy.random.RandomState.laplace
        • numpy.random.RandomState.logistic
        • numpy.random.RandomState.lognormal
        • numpy.random.RandomState.logseries
        • numpy.random.RandomState.multinomial
        • numpy.random.RandomState.multivariate_normal
        • numpy.random.RandomState.negative_binomial
        • numpy.random.RandomState.noncentral_chisquare
        • numpy.random.RandomState.noncentral_f
        • numpy.random.RandomState.normal
        • numpy.random.RandomState.pareto
        • numpy.random.RandomState.poisson
        • numpy.random.RandomState.power
        • numpy.random.RandomState.rayleigh
        • numpy.random.RandomState.standard_cauchy
        • numpy.random.RandomState.standard_exponential
        • numpy.random.RandomState.standard_gamma
        • numpy.random.RandomState.standard_normal
        • numpy.random.RandomState.standard_t
        • numpy.random.RandomState.triangular
        • numpy.random.RandomState.uniform
        • numpy.random.RandomState.vonmises
        • numpy.random.RandomState.wald
        • numpy.random.RandomState.weibull
        • numpy.random.RandomState.zipf
        • numpy.random.beta
        • numpy.random.binomial
        • numpy.random.bytes
        • numpy.random.chisquare
        • numpy.random.choice
        • numpy.random.dirichlet
        • numpy.random.exponential
        • numpy.random.f
        • numpy.random.gamma
        • numpy.random.geometric
        • numpy.random.get_state
        • numpy.random.gumbel
        • numpy.random.hypergeometric
        • numpy.random.laplace
        • numpy.random.logistic
        • numpy.random.lognormal
        • numpy.random.logseries
        • numpy.random.multinomial
        • numpy.random.multivariate_normal
        • numpy.random.negative_binomial
        • numpy.random.noncentral_chisquare
        • numpy.random.noncentral_f
        • numpy.random.normal
        • numpy.random.pareto
        • numpy.random.permutation
        • numpy.random.poisson
        • numpy.random.power
        • numpy.random.rand
        • numpy.random.randint
        • numpy.random.randn
        • numpy.random.random
        • numpy.random.random_integers
        • numpy.random.random_sample
        • numpy.random.ranf
        • numpy.random.rayleigh
        • numpy.random.sample
        • numpy.random.seed
        • numpy.random.set_state
        • numpy.random.shuffle
        • numpy.random.standard_cauchy
        • numpy.random.standard_exponential
        • numpy.random.standard_gamma
        • numpy.random.standard_normal
        • numpy.random.standard_t
        • numpy.random.triangular
        • numpy.random.uniform
        • numpy.random.vonmises
        • numpy.random.wald
        • numpy.random.weibull
        • numpy.random.zipf
      • Bit generators
      • Upgrading PCG64 with PCG64DXSM
      • Compatibility policy
      • Parallel Applications
      • Multithreaded Generation
      • What’s new or different
      • Comparing Performance
      • C API for random
      • Examples of using Numba, Cython, CFFI
    • Set routines
    • Sorting, searching, and counting
    • Statistics
    • Test support
    • Window functions
  • Typing (numpy.typing)
  • Packaging
  • NumPy C-API
  • Array API standard compatibility
  • CPU/SIMD optimizations
  • Thread Safety
  • Global Configuration Options
  • NumPy security
  • Testing guidelines
  • Status of numpy.distutils and migration advice
  • numpy.distutils user guide
  • NumPy and SWIG
  • NumPy reference
  • NumPy’s module structure
  • Random sampling
  • Legacy random generation
  • numpy.random.choice
numpy.random.choice# random.choice(a, size=None, replace=True, p=None)#

Generates a random sample from a given 1-D array

Note

New code should use the choice method of a Generator instance instead; please see the Quick start.

Warning

This function uses the C-long dtype, which is 32bit on windows and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones). Since NumPy 2.0, NumPy’s default integer is 32bit on 32bit platforms and 64bit on 64bit platforms.

Parameters: a1-D array-like or int

If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if it were np.arange(a)

sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

replaceboolean, optional

Whether the sample is with or without replacement. Default is True, meaning that a value of a can be selected multiple times.

p1-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.

Returns: samplessingle item or ndarray

The generated random samples

Raises: ValueError

If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size

See also

randint, shuffle, permutation random.Generator.choice

which should be used in new code

Notes

Setting user-specified probabilities through p uses a more general but less efficient sampler than the default. The general sampler produces a different sample than the optimized sampler even if each element of p is 1 / len(a).

Sampling random rows from a 2-D array is not possible with this function, but is possible with Generator.choice through its axis keyword.

Examples

Try it in your browser!

Generate a uniform random sample from np.arange(5) of size 3:

>>> np.random.choice(5, 3) array([0, 3, 4]) # random >>> #This is equivalent to np.random.randint(0,5,3)

Generate a non-uniform random sample from np.arange(5) of size 3:

>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) # random

Generate a uniform random sample from np.arange(5) of size 3 without replacement:

>>> np.random.choice(5, 3, replace=False) array([3,1,0]) # random >>> #This is equivalent to np.random.permutation(np.arange(5))[:3]

Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:

>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) array([2, 3, 0]) # random

Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance:

>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random dtype='<U11') Go BackOpen In Tab On this page
  • random.choice

Từ khóa » Np Choice