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

前端 未结 8 1385
粉色の甜心
粉色の甜心 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:02

    Based on your comment:

    The sample is already a. I want to work directly with a so that I can control how many elements are still left and perform other operations with a. – HappyPy

    it sounds to me like you're interested in working with a after n randomly selected elements are removed. Instead, why not work with N = len(a) - n randomly selected elements from a? Since you want them to still be in the original order, you can select from indices like in @CTZhu's answer, but then sort them and grab from the original list:

    import numpy as np
    n = 3 #number to 'remove'
    a = np.array([1,4,1,3,3,2,1,4])
    i = np.random.choice(np.arange(a.size), a.size-n, replace=False)
    i.sort()
    a[i]
    #array([1, 4, 1, 3, 1])
    

    So now you can save that as a again:

    a = a[i]
    

    and work with a with n elements removed.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题