Dipto Dipto - 1 year ago 420
Python Question

shuffle vs permute numpy

What is the difference between


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

If I want to generate random permutations of x, then what is the difference between

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download