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

前端 未结 8 1397
粉色の甜心
粉色の甜心 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.

提交回复
热议问题