how to get the index of numpy.random.choice? - python

前端 未结 8 1406
粉色の甜心
粉色の甜心 2021-02-02 12:31

Is it possible to modify the numpy.random.choice function in order to make it return the index of the chosen element? Basically, I want to create a list and select elements ran

8条回答
  •  佛祖请我去吃肉
    2021-02-02 12:44

    numpy.random.choice(a, size=however_many, replace=False)
    

    If you want a sample without replacement, just ask numpy to make you one. Don't loop and draw items repeatedly. That'll produce bloated code and horrible performance.

    Example:

    >>> a = numpy.arange(10)
    >>> a
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> numpy.random.choice(a, size=5, replace=False)
    array([7, 5, 8, 6, 2])
    

    On a sufficiently recent NumPy (at least 1.17), you should use the new randomness API, which fixes a longstanding performance issue where the old API's replace=False code path unnecessarily generated a complete permutation of the input under the hood:

    rng = numpy.random.default_rng()
    result = rng.choice(a, size=however_many, replace=False)
    

提交回复
热议问题