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

前端 未结 8 1389
粉色の甜心
粉色の甜心 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 13:04

    Regarding your first question, you can work the other way around, randomly choose from the index of the array a and then fetch the value.

    >>> a = [1,4,1,3,3,2,1,4]
    >>> a = np.array(a)
    >>> random.choice(arange(a.size))
    6
    >>> a[6]
    

    But if you just need random sample without replacement, replace=False will do. Can't remember when it was firstly added to random.choice, might be 1.7.0. So if you are running very old numpy it may not work. Keep in mind the default is replace=True

提交回复
热议问题