Select cells randomly from NumPy array - without replacement

前端 未结 6 1059
萌比男神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 16:53

    Use random.sample to generates ints in 0 .. A.size with no duplicates, then split them to index pairs:

    import random
    import numpy as np
    
    def randint2_nodup( nsample, A ):
        """ uniform int pairs, no dups:
            r = randint2_nodup( nsample, A )
            A[r]
            for jk in zip(*r):
                ... A[jk]
        """
        assert A.ndim == 2
        sample = np.array( random.sample( xrange( A.size ), nsample ))  # nodup ints
        return sample // A.shape[1], sample % A.shape[1]  # pairs
    
    
    if __name__ == "__main__":
        import sys
    
        nsample = 8
        ncol = 5
        exec "\n".join( sys.argv[1:] )  # run this.py N= ...
        A = np.arange( 0, 2*ncol ).reshape((2,ncol))
    
        r = randint2_nodup( nsample, A )
        print "r:", r
        print "A[r]:", A[r]
        for jk in zip(*r):
            print jk, A[jk]
    

提交回复
热议问题