Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

python - shuffle vs permute numpy

What is the difference between numpy.random.shuffle(x) and numpy.random.permutation(x)?

I have read the doc pages but I could not understand if there was any difference between the two when I just want to randomly shuffle the elements of an array.

To be more precise suppose I have an array x=[1,4,2,8].

If I want to generate random permutations of x, then what is the difference between shuffle(x) and permutation(x)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

np.random.permutation has two differences from np.random.shuffle:

  • if passed an array, it will return a shuffled copy of the array; np.random.shuffle shuffles the array inplace
  • if passed an integer, it will return a shuffled range i.e. np.random.shuffle(np.arange(n))

If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly.

The source code might help to understand this:

3280        def permutation(self, object x):
...
3307            if isinstance(x, (int, np.integer)):
3308                arr = np.arange(x)
3309            else:
3310                arr = np.array(x)
3311            self.shuffle(arr)
3312            return arr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...