Select cells randomly from NumPy array - without replacement

前端 未结 6 1058
萌比男神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:11

    Extending the nice answer from @WoLpH

    For a 2D array I think it will depend on what you want or need to know about the indices.

    You could do something like this:

    data = np.arange(25).reshape((5,5))
    
    x, y  = np.where( a = a)
    idx = zip(x,y)
    np.random.shuffle(idx)
    

    OR

    data = np.arange(25).reshape((5,5))
    
    grid = np.indices(data.shape)
    idx = zip( grid[0].ravel(), grid[1].ravel() )
    np.random.shuffle(idx)
    

    You can then use the list idx to iterate over randomly ordered 2D array indices as you wish, and to get the values at that index out of the data which remains unchanged.

    Note: You could also generate the randomly ordered indices via itertools.product too, in case you are more comfortable with this set of tools.

提交回复
热议问题