Select cells randomly from NumPy array - without replacement

前端 未结 6 1065
萌比男神i
萌比男神i 2021-02-19 16:41

I\'m writing some modelling routines in NumPy that need to select cells randomly from a NumPy array and do some processing on them. All cells must be selected without replacemen

6条回答
  •  耶瑟儿~
    2021-02-19 17:18

    All of these answers seemed a little convoluted to me.

    I'm assuming that you have a multi-dimensional array from which you want to generate an exhaustive list of indices. You'd like these indices shuffled so you can then access each of the array elements in a randomly order.

    The following code will do this in a simple and straight-forward manner:

    #!/usr/bin/python
    import numpy as np
    
    #Define a two-dimensional array
    #Use any number of dimensions, and dimensions of any size
    d=numpy.zeros(30).reshape((5,6))
    
    #Get a list of indices for an array of this shape
    indices=list(np.ndindex(d.shape))
    
    #Shuffle the indices in-place
    np.random.shuffle(indices)
    
    #Access array elements using the indices to do cool stuff
    for i in indices:
      d[i]=5
    
    print d
    

    Printing d verified that all elements have been accessed.

    Note that the array can have any number of dimensions and that the dimensions can be of any size.

    The only downside to this approach is that if d is large, then indices may become pretty sizable. Therefore, it would be nice to have a generator. Sadly, I can't think of how to build a shuffled iterator off-handedly.

提交回复
热议问题